using System.Diagnostics;
using ClaudeDo.Data;
using ClaudeDo.Ui.Localization;
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 IWorkerClient _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 PlanningInitialPromptPath { get; } = PromptFiles.PathFor(PromptKind.PlanningInitial);
    public string RetryPromptPath { get; } = PromptFiles.PathFor(PromptKind.Retry);
    public string DailyPrepPromptPath { get; } = PromptFiles.PathFor(PromptKind.DailyPrep);
    public string WeeklyReportPromptPath { get; } = PromptFiles.PathFor(PromptKind.WeeklyReport);

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

    [RelayCommand]
    private async Task RestoreDefaultAgents()
    {
        IsBusy = true; StatusMessage = "";
        try
        {
            var r = await _worker.RestoreDefaultAgentsAsync();
            if (r is null) StatusMessage = Loc.T("vm.filesTab.workerOffline");
            else if (r.Copied == 0 && r.Skipped == 0) StatusMessage = Loc.T("vm.filesTab.noneBundled");
            else if (r.Copied == 0) StatusMessage = Loc.T("vm.filesTab.allPresent");
            else StatusMessage = Loc.T("vm.filesTab.restored", r.Copied);
            await _worker.RefreshAgentsAsync();
        }
        catch (Exception ex) { StatusMessage = Loc.T("vm.filesTab.restoreFailed", 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 = Loc.T("vm.filesTab.openFailed", ex.Message); }
    }
}
