using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;

namespace DH.Commons.Helper
{
    public static class SchemeHelper
    {
        private const string DefaultSchemeName = "默认方案";
        private static readonly string ConfigFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "schemes.json");

        /// <summary>
        /// 方案配置数据结构
        /// </summary>
        private class SchemeConfig
        {
            public List<string> Schemes { get; set; } = new List<string>();
            public string CurrentScheme { get; set; } = DefaultSchemeName;
        }

        /// <summary>
        /// 初始化配置(首次运行时调用)
        /// </summary>
        public static void Initialize()
        {
            if (!File.Exists(ConfigFilePath))
            {
                var defaultConfig = new SchemeConfig
                {
                    Schemes = new List<string> { DefaultSchemeName },
                    CurrentScheme = DefaultSchemeName
                };
                SaveConfig(defaultConfig);
            }
        }

        /// <summary>
        /// 获取所有方案
        /// </summary>
        public static List<string> GetAllSchemes()
        {
            var config = LoadConfig();
            return config.Schemes ?? new List<string>();
        }

        /// <summary>
        /// 添加新方案
        /// </summary>
        public static void AddScheme(string schemeName)
        {
            if (string.IsNullOrWhiteSpace(schemeName))
                throw new ArgumentException("方案名称无效");

            var config = LoadConfig();

            if (config.Schemes.Contains(schemeName))
                throw new InvalidOperationException($"方案 {schemeName} 已存在");

            config.Schemes.Add(schemeName);
            SaveConfig(config);
        }

        /// <summary>
        /// 设置当前方案
        /// </summary>
        public static void SetCurrentScheme(string schemeName)
        {
            var config = LoadConfig();

            if (!config.Schemes.Contains(schemeName))
                throw new KeyNotFoundException($"方案 {schemeName} 不存在");

            config.CurrentScheme = schemeName;
            SaveConfig(config);
        }

        /// <summary>
        /// 获取当前方案
        /// </summary>
        public static string GetCurrentScheme()
        {
            var config = LoadConfig();
            return !string.IsNullOrEmpty(config.CurrentScheme)
                ? config.CurrentScheme
                : DefaultSchemeName;
        }

        /// <summary>
        /// 删除指定方案
        /// </summary>
        public static void DeleteScheme(string schemeName)
        {
            if (string.IsNullOrWhiteSpace(schemeName))
                throw new ArgumentException("方案名称无效");

            var config = LoadConfig();

            if (!config.Schemes.Contains(schemeName))
                throw new KeyNotFoundException($"方案 {schemeName} 不存在");

            // 如果是当前方案,需要先切换
            if (config.CurrentScheme == schemeName)
            {
                var otherScheme = config.Schemes.FirstOrDefault(s => s != schemeName);
                if (otherScheme != null)
                {
                    config.CurrentScheme = otherScheme;
                }
                else
                {
                    config.CurrentScheme = DefaultSchemeName;
                    if (!config.Schemes.Contains(DefaultSchemeName))
                    {
                        config.Schemes.Add(DefaultSchemeName);
                    }
                }
            }

            config.Schemes.Remove(schemeName);
            SaveConfig(config);
        }

        /// <summary>
        /// 加载配置文件
        /// </summary>
        private static SchemeConfig LoadConfig()
        {
            if (!File.Exists(ConfigFilePath))
            {
                Initialize();
            }

            try
            {
                string json = File.ReadAllText(ConfigFilePath);
                return JsonConvert.DeserializeObject<SchemeConfig>(json) ?? new SchemeConfig();
            }
            catch
            {
                // 如果读取失败,返回默认配置
                return new SchemeConfig
                {
                    Schemes = new List<string> { DefaultSchemeName },
                    CurrentScheme = DefaultSchemeName
                };
            }
        }

        /// <summary>
        /// 保存配置文件
        /// </summary>
        private static void SaveConfig(SchemeConfig config)
        {
            try
            {
                string json = JsonConvert.SerializeObject(config, Formatting.Indented);
                File.WriteAllText(ConfigFilePath, json);
            }
            catch (Exception ex)
            {
                // 处理保存失败的情况
                throw new InvalidOperationException("保存方案配置失败", ex);
            }
        }
    }
}