using System;
using System.IO;
using Newtonsoft.Json;

namespace MusicBeePlugin.Clouseau.Core
{
    /// <summary>
    /// Settings manager for Clouseau plugin.
    /// Loads/saves settings from settings.json using Newtonsoft.Json.
    /// </summary>
    public class ClouseauSettings
    {
        private static readonly string SettingsFileName = "settings.json";

        // Settings sections
        public LoggingSettings Logging { get; set; } = new LoggingSettings();
        public EventsSettings Events { get; set; } = new EventsSettings();
        public SystemMetricsSettings SystemMetrics { get; set; } = new SystemMetricsSettings();
        public PerformanceSettings Performance { get; set; } = new PerformanceSettings();
        public UISettings UI { get; set; } = new UISettings();
        public ExportSettings Export { get; set; } = new ExportSettings();
        public AlertsSettings Alerts { get; set; } = new AlertsSettings();
        public DebuggingSettings Debugging { get; set; } = new DebuggingSettings();
        public AdvancedSettings Advanced { get; set; } = new AdvancedSettings();

        /// <summary>
        /// Load settings from JSON file in data directory
        /// </summary>
        public static ClouseauSettings Load(string dataPath)
        {
            var settingsPath = Path.Combine(dataPath, SettingsFileName);

            try
            {
                if (File.Exists(settingsPath))
                {
                    var json = File.ReadAllText(settingsPath);
                    var settings = JsonConvert.DeserializeObject<ClouseauSettings>(json);
                    if (settings != null)
                    {
                        return settings;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Failed to load settings: {ex.Message}");
            }

            // Return defaults if load fails
            return new ClouseauSettings();
        }

        /// <summary>
        /// Save settings to JSON file in data directory
        /// </summary>
        public void Save(string dataPath)
        {
            var settingsPath = Path.Combine(dataPath, SettingsFileName);

            try
            {
                var json = JsonConvert.SerializeObject(this, Formatting.Indented);
                File.WriteAllText(settingsPath, json);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Failed to save settings: {ex.Message}");
            }
        }
    }

    #region Settings Section Classes

    public class LoggingSettings
    {
        public bool Enabled { get; set; } = true;
        public string Level { get; set; } = "Verbose";
        public LoggingOutputsSettings Outputs { get; set; } = new LoggingOutputsSettings();
        public LoggingFormatSettings Format { get; set; } = new LoggingFormatSettings();
    }

    public class LoggingOutputsSettings
    {
        public LogFileSettings FileLog { get; set; } = new LogFileSettings();
        public LogFileSettings EventsLog { get; set; } = new LogFileSettings();
        public LogFileSettings MetricsLog { get; set; } = new LogFileSettings();
        public LogFileSettings JsonLog { get; set; } = new LogFileSettings();
        public LogFileSettings ErrorLog { get; set; } = new LogFileSettings();
        public LogFileSettings PerformanceLog { get; set; } = new LogFileSettings();
        public LogFileSettings ApiLog { get; set; } = new LogFileSettings();
        public LogFileSettings TraceLog { get; set; } = new LogFileSettings();
    }

    public class LogFileSettings
    {
        public bool Enabled { get; set; } = true;
        public string Path { get; set; } = "";
        public int MaxSizeMB { get; set; } = 50;
        public int MaxArchiveFiles { get; set; } = 30;
        public string ArchiveEvery { get; set; } = "Day";
    }

    public class LoggingFormatSettings
    {
        public string TimestampFormat { get; set; } = "yyyy-MM-dd HH:mm:ss.fff";
        public bool IncludeThreadId { get; set; } = true;
        public bool IncludeProcessId { get; set; } = true;
        public bool IncludeMachineName { get; set; } = false;
        public bool IncludeCallSite { get; set; } = true;
    }

    public class EventsSettings
    {
        public bool SubscribeAll { get; set; } = true;
        public NotificationFlagsSettings NotificationFlags { get; set; } = new NotificationFlagsSettings();
        public CaptureContextSettings CaptureContext { get; set; } = new CaptureContextSettings();
    }

    public class NotificationFlagsSettings
    {
        public bool PlayerEvents { get; set; } = true;
        public bool DataStreamEvents { get; set; } = true;
        public bool TagEvents { get; set; } = true;
        public bool DownloadEvents { get; set; } = true;
    }

    public class CaptureContextSettings
    {
        public bool IncludeTrackMetadata { get; set; } = true;
        public bool IncludePlaybackState { get; set; } = true;
        public bool IncludeQueueInfo { get; set; } = true;
        public bool IncludeVolumeState { get; set; } = true;
        public bool IncludeTimestamp { get; set; } = true;
        public bool IncludeSourceFile { get; set; } = true;
    }

    public class SystemMetricsSettings
    {
        public bool Enabled { get; set; } = true;
        public int CollectionIntervalMs { get; set; } = 5000;
        public int LogIntervalMs { get; set; } = 30000;
        public CpuMetricsSettings Cpu { get; set; } = new CpuMetricsSettings();
        public MemoryMetricsSettings Memory { get; set; } = new MemoryMetricsSettings();
        public DiskMetricsSettings Disk { get; set; } = new DiskMetricsSettings();
        public NetworkMetricsSettings Network { get; set; } = new NetworkMetricsSettings();
        public ClrMetricsSettings Clr { get; set; } = new ClrMetricsSettings();
        public AudioMetricsSettings Audio { get; set; } = new AudioMetricsSettings();
    }

    public class CpuMetricsSettings
    {
        public bool Enabled { get; set; } = true;
        public bool TotalUsage { get; set; } = true;
        public bool PerCoreUsage { get; set; } = true;
        public bool ProcessUsage { get; set; } = true;
    }

    public class MemoryMetricsSettings
    {
        public bool Enabled { get; set; } = true;
        public bool TotalPhysical { get; set; } = true;
        public bool AvailablePhysical { get; set; } = true;
        public bool UsedPhysical { get; set; } = true;
        public bool PercentUsed { get; set; } = true;
    }

    public class DiskMetricsSettings
    {
        public bool Enabled { get; set; } = true;
        public string[] Drives { get; set; } = new[] { "C:" };
        public bool TotalSpace { get; set; } = true;
        public bool FreeSpace { get; set; } = true;
        public bool PercentFree { get; set; } = true;
    }

    public class NetworkMetricsSettings
    {
        public bool Enabled { get; set; } = true;
        public bool BytesReceivedPerSec { get; set; } = true;
        public bool BytesSentPerSec { get; set; } = true;
    }

    public class ClrMetricsSettings
    {
        public bool Enabled { get; set; } = true;
        public bool GcTimePercent { get; set; } = true;
        public bool AllocatedBytesPerSec { get; set; } = true;
    }

    public class AudioMetricsSettings
    {
        public bool Enabled { get; set; } = true;
        public bool DeviceInfo { get; set; } = true;
        public bool BufferStatus { get; set; } = true;
        public bool SampleRate { get; set; } = true;
        public bool BitDepth { get; set; } = true;
        public bool Channels { get; set; } = true;
        public bool Latency { get; set; } = true;
    }

    public class PerformanceSettings
    {
        public bool Enabled { get; set; } = true;
        public bool TrackApiCalls { get; set; } = true;
        public bool TrackEventProcessing { get; set; } = true;
        public int WarnThresholdMs { get; set; } = 100;
        public int ErrorThresholdMs { get; set; } = 500;
        public bool SlowOperationLogging { get; set; } = true;
    }

    public class UISettings
    {
        public PanelSettings Panel { get; set; } = new PanelSettings();
    }

    public class PanelSettings
    {
        public bool Enabled { get; set; } = true;
        public bool AutoScroll { get; set; } = true;
        public int MaxDisplayedEntries { get; set; } = 1000;
        public int RefreshIntervalMs { get; set; } = 100;
        public bool ShowTimestamp { get; set; } = true;
        public bool ShowCategory { get; set; } = true;
        public bool ShowSourceFile { get; set; } = false;
        public bool ColorCodeByCategory { get; set; } = true;
        public bool ColorCodeByLevel { get; set; } = true;
    }

    public class ExportSettings
    {
        public bool Enabled { get; set; } = true;
        public string[] Formats { get; set; } = new[] { "json", "csv", "txt" };
        public string DefaultFormat { get; set; } = "json";
        public bool IncludeMetrics { get; set; } = true;
        public bool IncludeSystemInfo { get; set; } = true;
        public bool CompressionEnabled { get; set; } = true;
        public AutoExportSettings AutoExport { get; set; } = new AutoExportSettings();
    }

    public class AutoExportSettings
    {
        public bool Enabled { get; set; } = false;
        public int IntervalMinutes { get; set; } = 60;
        public string Path { get; set; } = "";
    }

    public class AlertsSettings
    {
        public bool Enabled { get; set; } = true;
        public AlertCondition[] Conditions { get; set; } = new AlertCondition[0];
    }

    public class AlertCondition
    {
        public string Name { get; set; } = "";
        public string Metric { get; set; } = "";
        public string Operator { get; set; } = ">";
        public double Threshold { get; set; } = 0;
        public int DurationSeconds { get; set; } = 0;
        public string Action { get; set; } = "log";
    }

    public class DebuggingSettings
    {
        public bool Enabled { get; set; } = true;
        public bool BreakOnError { get; set; } = false;
        public bool VerboseExceptions { get; set; } = true;
        public int StackTraceDepth { get; set; } = 10;
        public bool DumpOnCrash { get; set; } = true;
        public string DumpPath { get; set; } = "";
        public bool AttachDebugger { get; set; } = false;
    }

    public class AdvancedSettings
    {
        public int BufferSize { get; set; } = 10000;
        public int FlushIntervalMs { get; set; } = 1000;
        public bool AsyncLogging { get; set; } = true;
        public bool UseHighResolutionTimer { get; set; } = true;
        public bool CaptureEnvironmentOnStartup { get; set; } = true;
        public bool CaptureLoadedAssemblies { get; set; } = true;
        public bool CaptureWindowsVersion { get; set; } = true;
        public bool CaptureMusicBeeVersion { get; set; } = true;
        /// <summary>
        /// If true (default), delete all logs and data when plugin is uninstalled.
        /// If false, keep logs and data for future analysis.
        /// </summary>
        public bool DeleteDataOnUninstall { get; set; } = true;
    }

    #endregion
}
