using System.Collections.ObjectModel;
using System.Reflection;
using ClawdDotNet.App;
using ClawdDotNet.Core.Storage;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace ClawdDotNet.Desktop.ViewModels;

public sealed record AssemblyInfoItem(string ShortName, int BuildNumber, string BuildDate, string Changes);

/// <summary>
/// Ansichtsmodell für die Info-Seite (Version, Build-Informationen, Instanz-Details).
/// </summary>
public sealed partial class InfoPageViewModel : PageViewModel
{
    [ObservableProperty]
    private string _appVersion = "—";

    [ObservableProperty]
    private string _buildSummary = "—";

    [ObservableProperty]
    private string _instanceName = "—";

    [ObservableProperty]
    private string _instanceId = "—";

    [ObservableProperty]
    private string _instancePath = "—";

    [ObservableProperty]
    private string _logDirectory = "—";

    [ObservableProperty]
    private string _openRouterStatus = "—";

    public ObservableCollection<AssemblyInfoItem> Assemblies { get; } = [];

    public InfoPageViewModel() : this(null) { }

    public InfoPageViewModel(AppHost? host) : base("Info")
    {
        AppVersion = AppHost.AppVersion;
        BuildSummary = AppHost.BuildSummary;

        if (host is not null)
        {
            InstanceName = host.Instance.InstanceName;
            InstanceId = host.Instance.InstanceId;
            InstancePath = host.InstancePath;
            LogDirectory = host.LogDirectory;
            OpenRouterStatus = host.Engine is null
                ? "Deaktiviert (kein API-Key hinterlegt)"
                : "Aktiv (AgentEngine bereit)";
        }
        else
        {
            InstanceName = "Entwurfsmodus";
            InstanceId = "00000000-0000-0000-0000-000000000000";
            InstancePath = @"C:\ClawdDotNet\Instances\Default";
            LogDirectory = @"C:\ClawdDotNet\Logs";
            OpenRouterStatus = "Entwurf";
        }

        LoadAssemblyBuildInfos();
    }

    /// <summary>
    /// Fruehere Menueleiste, Punkt „Bearbeiten &gt; Instanz-Ordner oeffnen". Der Entwurf
    /// kennt keine Menueleiste mehr; der Befehl sitzt jetzt dort, wo auch der Pfad steht.
    /// </summary>
    [RelayCommand]
    private void OpenInstanceFolder()
    {
        if (!Directory.Exists(InstancePath)) return;
        SystemShell.OpenFolder(InstancePath);
    }

    private void LoadAssemblyBuildInfos()
    {
        Assemblies.Clear();

        foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()
            .Where(a => a.GetName().Name?.StartsWith("ClawdDotNet") == true)
            .OrderBy(a => a.GetName().Name))
        {
            var name = asm.GetName().Name!;
            var shortName = name.Replace("ClawdDotNet.", "").Replace("Tools.", "");

            var buildDate = asm.GetCustomAttributes(typeof(AssemblyMetadataAttribute), false)
                .OfType<AssemblyMetadataAttribute>()
                .FirstOrDefault(a => a.Key == "BuildDate")?.Value ?? "?";

            var buildInfoType = asm.GetType(asm.GetName().Name + ".BuildInfo");
            var buildNum = buildInfoType?.GetField("Build")?.GetValue(null) as int? ?? 0;
            var changes = buildInfoType?.GetField("Changes")?.GetValue(null) as string ?? "—";

            Assemblies.Add(new AssemblyInfoItem(shortName, buildNum, buildDate, changes));
        }
    }
}
