using System;
using System.Diagnostics;
using System.IO;
using ClaudeDo.Ui.Services;
using CommunityToolkit.Mvvm.Input;

namespace ClaudeDo.Ui.ViewModels.Modals;

public sealed partial class WorkerConnectionModalViewModel : ViewModelBase
{
    private readonly WorkerLocator _workerLocator;
    private readonly InstallerLocator _installerLocator;

    public WorkerConnectionModalViewModel(WorkerLocator workerLocator, InstallerLocator installerLocator)
    {
        _workerLocator = workerLocator;
        _installerLocator = installerLocator;
    }

    public Action? CloseAction { get; set; }

    [RelayCommand] private void Close() => CloseAction?.Invoke();

    [RelayCommand]
    private void StartWorker()
    {
        var exe = _workerLocator.Find();
        if (exe is null) return;
        try { Process.Start(new ProcessStartInfo(exe) { UseShellExecute = true }); }
        catch { /* nothing useful to show */ }
        CloseAction?.Invoke();
    }

    [RelayCommand]
    private void RerunInstaller()
    {
        var path = _installerLocator.Find();
        if (path is null) return;
        try
        {
            // See IslandsShellViewModel.UpdateNow: an inherited CWD inside the install dir
            // makes the installer block its own app\ rename.
            Process.Start(new ProcessStartInfo(path)
            {
                UseShellExecute = true,
                WorkingDirectory = Path.GetTempPath(),
            });
            Environment.Exit(0);
        }
        catch { /* nothing useful to show */ }
    }
}
