using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
using ClaudeDo.Installer.Core;
using ClaudeDo.Installer.Localization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace ClaudeDo.Installer.Checks;

public sealed class CheckRowViewModel
{
    public CheckRowViewModel(CheckResult result)
    {
        var loc = TrExtension.Localizer;
        Status = result.Status;
        Severity = result.Severity;
        Title = loc?[result.TitleKey] ?? result.TitleKey;
        Message = result.Message;
        Hint = result.HintKey is not null ? loc?[result.HintKey] ?? result.HintKey : null;
        HelpUrl = result.HelpUrl;
        StatusBrush = ResolveBrush(Status, Severity);
    }

    public CheckStatus Status { get; }
    public CheckSeverity Severity { get; }
    public string Title { get; }
    public string Message { get; }
    public string? Hint { get; }
    public string? HelpUrl { get; }
    public Brush StatusBrush { get; }

    private static Brush ResolveBrush(CheckStatus status, CheckSeverity severity)
    {
        var key = status switch
        {
            CheckStatus.Ok => "StatusGreenBrush",
            CheckStatus.Unknown => "StatusGrayBrush",
            CheckStatus.Failed when severity == CheckSeverity.Error => "StatusRedBrush",
            CheckStatus.Failed => "StatusOrangeBrush",
            _ => "StatusGrayBrush",
        };
        return Application.Current?.Resources[key] as Brush ?? Brushes.Gray;
    }
}

/// <summary>
/// Shared presentation logic for the environment check list: running the check pass, tracking
/// busy/summary state, and the row collection. Composed (not subclassed) by every page that
/// hosts a check list — <see cref="Pages.SystemCheckPage.SystemCheckPageViewModel"/> and
/// <see cref="Pages.DiagnosePage.DiagnosePageViewModel"/> — so the run logic exists exactly once.
/// </summary>
public partial class CheckListViewModel : ObservableObject
{
    private readonly InstallContext _context;
    private readonly Func<EnvironmentCheckService> _checkServiceFactory;

    public ObservableCollection<CheckRowViewModel> Rows { get; } = [];

    /// <summary>Report of the most recent run, null before the first one. Hosts that need the raw
    /// results (the wizard's "Claude Help Me" button) read it instead of running the checks again.</summary>
    public EnvironmentCheckReport? LastReport { get; private set; }

    [ObservableProperty] private bool _isRunning;
    [ObservableProperty] private bool _hasRun;
    [ObservableProperty] private bool _hasBlockingError;
    [ObservableProperty] private string _summary = string.Empty;

    public CheckListViewModel(InstallContext context, Func<EnvironmentCheckService> checkServiceFactory)
    {
        _context = context;
        _checkServiceFactory = checkServiceFactory;
    }

    partial void OnIsRunningChanged(bool value) => RunChecksCommand.NotifyCanExecuteChanged();

    [RelayCommand(CanExecute = nameof(CanRunChecks))]
    private async Task RunChecksAsync()
    {
        if (IsRunning) return;

        IsRunning = true;
        Summary = TrExtension.Localizer?["installer.systemCheck.summary.running"] ?? "Checking your system…";

        try
        {
            var service = _checkServiceFactory();
            var report = await service.RunAllAsync(_context, CancellationToken.None);

            Rows.Clear();
            foreach (var result in report.Results)
                Rows.Add(new CheckRowViewModel(result));

            LastReport = report;
            OnPropertyChanged(nameof(LastReport));
            HasBlockingError = report.HasBlockingError;
            Summary = BuildSummary(report);
            HasRun = true;
        }
        finally
        {
            IsRunning = false;
        }
    }

    private bool CanRunChecks() => !IsRunning;

    private static string BuildSummary(EnvironmentCheckReport report)
    {
        var loc = TrExtension.Localizer;

        var blocking = report.Results
            .Where(r => r.Severity == CheckSeverity.Error && r.Status == CheckStatus.Failed)
            .ToList();
        if (blocking.Count > 0)
        {
            var names = string.Join(", ", blocking.Select(r => loc?[r.TitleKey] ?? r.TitleKey));
            return loc?.Get("installer.systemCheck.summary.blocking", blocking.Count, names)
                   ?? $"{blocking.Count} problem(s) must be fixed: {names}";
        }

        var warnings = report.Results.Count(r => r.Severity == CheckSeverity.Warning && r.Status == CheckStatus.Failed);
        if (warnings > 0)
        {
            return loc?.Get("installer.systemCheck.summary.warnings", warnings)
                   ?? $"{warnings} warning(s) found.";
        }

        return loc?["installer.systemCheck.summary.ok"] ?? "Everything looks good.";
    }

    [RelayCommand]
    private static void OpenHelpUrl(string? url)
    {
        if (string.IsNullOrEmpty(url)) return;
        Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
    }
}
