using ClawdDotNet.App;
using ClawdDotNet.App.Settings;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;

namespace ClawdDotNet.Desktop.ViewModels;

/// <summary>
/// Ansichtsmodell für die Einstellungen-Seite (Anwendungs- und Instanz-Einstellungen).
/// </summary>
public sealed partial class SettingsPageViewModel : PageViewModel
{
    private readonly AppHost? _host;
    private readonly ILogger? _logger;

    // ─── Allgemein & Pfade ───
    [ObservableProperty]
    private string _logDirectory = "";

    [ObservableProperty]
    private string _instancesDirectory = "";

    [ObservableProperty]
    private string _minimumLogLevel = "Info";

    [ObservableProperty]
    private int _maxLogLinesInUi = 2000;

    [ObservableProperty]
    private int _logRefreshIntervalMs = 500;

    // ─── API & OpenRouter ───
    [ObservableProperty]
    private string _openRouterBaseUrl = "https://openrouter.ai/api/v1/";

    [ObservableProperty]
    private int _statusCheckIntervalSeconds = 60;

    // Die Sicherungs-Einstellungen (Zielordner, Uhrzeit, Anzahl) stehen bewusst
    // NICHT hier, sondern allein auf der Sicherungs-Seite. Sie lagen frueher
    // doppelt vor: Die Felder waren aus der Ansicht bereits verschwunden, wurden
    // aber weiter beim Start gelesen und beim Speichern zurueckgeschrieben - wer
    // die Uhrzeit auf der Sicherungs-Seite aenderte und danach hier speicherte,
    // bekam den alten Wert zurueck.
    // ─── Deploymentcenter ───
    [ObservableProperty]
    private string _deploymentcenterUrl = "https://dc.mhdf.de";

    [ObservableProperty]
    private string _deploymentcenterToken = "";

    [ObservableProperty]
    private string _deploymentcenterEnvironment = "production";

    [ObservableProperty]
    private bool _errorReportingEnabled = true;

    [ObservableProperty]
    private bool _updateCheckEnabled = true;

    [ObservableProperty]
    private string _updateChannel = "prod";

    // ─── Lizenz ───
    [ObservableProperty]
    private string _licenseKey = "";

    // ─── Instanz-Einstellungen ───
    [ObservableProperty]
    private string _instanceName = "";

    [ObservableProperty]
    private string _openRouterApiKey = "";

    [ObservableProperty]
    private decimal _instanceDailyCostUsd;

    [ObservableProperty]
    private long _instanceDailyTokens;

    [ObservableProperty]
    private string _statusText = "Bereit";

    public List<string> LogLevels { get; } = ["Debug", "Info", "Warn", "Error"];
    public List<string> UpdateChannels { get; } = ["prod", "beta", "dev"];
    public List<string> Environments { get; } = ["production", "development", "staging"];

    public SettingsPageViewModel() : this(null) { }

    public SettingsPageViewModel(AppHost? host) : base("Einstellungen")
    {
        _host = host;

        if (host is not null)
        {
            _logger = host.LoggerFactory.CreateLogger("ClawdDotNet.Desktop.Settings");
            LoadFromHost();
        }
        else
        {
            StatusText = "Entwurfsmodus";
        }
    }

    [RelayCommand]
    private void LoadFromHost()
    {
        if (_host is null) return;

        var s = _host.Settings.AppSettings;
        LogDirectory = s.LogDirectory;
        InstancesDirectory = s.InstancesDirectory;
        MinimumLogLevel = s.MinimumLogLevel;
        MaxLogLinesInUi = s.MaxLogLinesInUi;
        LogRefreshIntervalMs = s.LogRefreshIntervalMs;
        OpenRouterBaseUrl = s.OpenRouterBaseUrl;
        StatusCheckIntervalSeconds = s.StatusCheckIntervalSeconds;
        DeploymentcenterUrl = s.DeploymentcenterUrl;
        DeploymentcenterToken = s.DeploymentcenterToken;
        DeploymentcenterEnvironment = s.DeploymentcenterEnvironment;
        ErrorReportingEnabled = s.ErrorReportingEnabled;
        UpdateCheckEnabled = s.UpdateCheckEnabled;
        UpdateChannel = s.UpdateChannel;
        LicenseKey = s.LicenseKey;

        var inst = _host.Instance;
        InstanceName = inst.InstanceName;
        OpenRouterApiKey = inst.OpenRouterApiKey;
        InstanceDailyCostUsd = inst.Budget.DailyCostUsd;
        InstanceDailyTokens = inst.Budget.DailyTokens;
    }

    [RelayCommand]
    private void SaveSettings()
    {
        if (_host is null) return;

        var s = _host.Settings.AppSettings;
        s.LogDirectory = LogDirectory.Trim();
        s.InstancesDirectory = InstancesDirectory.Trim();
        s.MinimumLogLevel = MinimumLogLevel;
        s.MaxLogLinesInUi = MaxLogLinesInUi;
        s.LogRefreshIntervalMs = LogRefreshIntervalMs;
        s.OpenRouterBaseUrl = OpenRouterBaseUrl.Trim();
        s.StatusCheckIntervalSeconds = StatusCheckIntervalSeconds;
        s.DeploymentcenterUrl = DeploymentcenterUrl.Trim();
        s.DeploymentcenterToken = DeploymentcenterToken.Trim();
        s.DeploymentcenterEnvironment = DeploymentcenterEnvironment.Trim();
        s.ErrorReportingEnabled = ErrorReportingEnabled;
        s.UpdateCheckEnabled = UpdateCheckEnabled;
        s.UpdateChannel = UpdateChannel;
        s.LicenseKey = LicenseKey.Trim();

        _host.Settings.Save();

        var inst = _host.Instance;
        inst.InstanceName = InstanceName.Trim();
        inst.OpenRouterApiKey = OpenRouterApiKey.Trim();
        inst.Budget.DailyCostUsd = InstanceDailyCostUsd;
        inst.Budget.DailyTokens = InstanceDailyTokens;

        _host.Directories.SaveInstanceConfig(_host.InstancePath, inst);

        _logger?.LogInformation("Einstellungen und Instanz-Konfiguration gespeichert.");
        StatusText = "Einstellungen erfolgreich gespeichert.";
    }
}
