using System.Diagnostics;
using ClaudeDo.Data;
using ClaudeDo.Ui.Services;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace ClaudeDo.Ui.ViewModels.Modals.Settings;

public sealed partial class FilesSettingsTabViewModel : ViewModelBase
{
    private readonly WorkerClient _worker;

    [ObservableProperty] private string _statusMessage = "";
    [ObservableProperty] private bool _isBusy;

    public string SystemPromptPath { get; } = PromptFiles.PathFor(PromptKind.System);
    public string PlanningPromptPath { get; } = PromptFiles.PathFor(PromptKind.Planning);
    public string AgentPromptPath { get; } = PromptFiles.PathFor(PromptKind.Agent);

    public FilesSettingsTabViewModel(WorkerClient worker) => _worker = worker;

    [RelayCommand]
    private async Task RestoreDefaultAgents()
    {
        IsBusy = true; StatusMessage = "";
        try
        {
            var r = await _worker.RestoreDefaultAgentsAsync();
            if (r is null) StatusMessage = "Worker offline.";
            else if (r.Copied == 0 && r.Skipped == 0) StatusMessage = "No default agents bundled.";
            else if (r.Copied == 0) StatusMessage = "All default agents already present.";
            else StatusMessage = $"Restored {r.Copied} default agent(s).";
            await _worker.RefreshAgentsAsync();
        }
        catch (Exception ex) { StatusMessage = $"Restore failed: {ex.Message}"; }
        finally { IsBusy = false; }
    }

    [RelayCommand]
    private void OpenPrompt(string? kindName)
    {
        if (!Enum.TryParse<PromptKind>(kindName, ignoreCase: true, out var kind)) return;
        try
        {
            PromptFiles.EnsureExists(kind);
            var path = PromptFiles.PathFor(kind);
            Process.Start(new ProcessStartInfo(path) { UseShellExecute = true });
        }
        catch (Exception ex) { StatusMessage = $"Open failed: {ex.Message}"; }
    }
}
