using System;
using System.Collections.Generic;
using Dapper;
using MySqlConnector;
using log4net;

namespace CncCollector.Config
{
    /// <summary>
    /// 从 cnc_sys_config 表加载运行时配置，覆盖 CollectorConfig 的默认值
    /// </summary>
    public static class ConfigLoader
    {
        private static readonly ILog _log = LogManager.GetLogger(typeof(ConfigLoader));

        /// <summary>
        /// 从数据库加载配置并覆盖 CollectorConfig 中的默认值
        /// </summary>
        /// <param name="connectionString">业务库连接字符串</param>
        /// <param name="config">要覆盖的配置对象</param>
        public static void LoadRuntimeConfig(string connectionString, CollectorConfig config)
        {
            try
            {
                using (var conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    var rows = conn.Query<KeyValuePair<string, string>>(
                        "SELECT config_key as `Key`, config_value as `Value` FROM cnc_sys_config");

                    foreach (var row in rows)
                    {
                        string key = row.Key;
                        string val = row.Value ?? "";

                        switch (key)
                        {
                            case "collector_api_port":
                                if (int.TryParse(val, out var port)) config.ApiPort = port;
                                break;
                            case "collector_api_key":
                                if (!string.IsNullOrEmpty(val)) config.ApiKey = val;
                                break;
                            case "heartbeat_interval":
                                if (int.TryParse(val, out var hb)) config.HeartbeatIntervalSeconds = hb;
                                break;
                            case "config_poll_interval":
                                if (int.TryParse(val, out var cp)) config.ConfigPollIntervalSeconds = cp;
                                break;
                            case "daily_summary_time":
                                if (!string.IsNullOrEmpty(val)) config.DailySummaryTime = val;
                                break;
                            case "collect_retry_count":
                                if (int.TryParse(val, out var rc)) config.CollectRetryCount = rc;
                                break;
                            case "collect_retry_interval":
                                if (int.TryParse(val, out var ri)) config.CollectRetryIntervalSeconds = ri;
                                break;
                            case "collect_fail_alert_threshold":
                                if (int.TryParse(val, out var ft)) config.CollectFailAlertThreshold = ft;
                                break;
                        }
                    }
                }

                _log.Info($"数据库配置加载完成: ApiPort={config.ApiPort}, Heartbeat={config.HeartbeatIntervalSeconds}s, "
                    + $"ConfigPoll={config.ConfigPollIntervalSeconds}s, SummaryTime={config.DailySummaryTime}, "
                    + $"RetryCount={config.CollectRetryCount}, RetryInterval={config.CollectRetryIntervalSeconds}s, "
                    + $"FailThreshold={config.CollectFailAlertThreshold}");
            }
            catch (Exception ex)
            {
                _log.Error("从数据库加载配置失败，将使用默认值", ex);
            }
        }
    }
}
