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

namespace CncCollector.Config
{
    /// <summary>
    /// 采集服务配置（从 collector.json 读取）
    /// </summary>
    public class CollectorConfig
    {
        /// <summary>业务库连接字符串</summary>
        [JsonProperty("businessConnection")]
        public string BusinessConnection { get; set; }

        /// <summary>日志库连接字符串</summary>
        [JsonProperty("logConnection")]
        public string LogConnection { get; set; }

        /// <summary>管理API端口</summary>
        [JsonProperty("apiPort")]
        public int ApiPort { get; set; } = 5800;

        /// <summary>服务间通信API Key</summary>
        [JsonProperty("apiKey")]
        public string ApiKey { get; set; } = "collector_api_key_2026";

        /// <summary>心跳上报间隔（秒）</summary>
        [JsonProperty("heartbeatIntervalSeconds")]
        public int HeartbeatIntervalSeconds { get; set; } = 10;

        /// <summary>配置轮询间隔（秒）</summary>
        [JsonProperty("configPollIntervalSeconds")]
        public int ConfigPollIntervalSeconds { get; set; } = 30;

        /// <summary>日终汇总执行时间（HH:mm格式）</summary>
        [JsonProperty("dailySummaryTime")]
        public string DailySummaryTime { get; set; } = "01:00";

        /// <summary>分析日志保留天数（0=不删除）</summary>
        public int AnalysisLogRetentionDays { get; set; } = 0;

        /// <summary>周期日志保留天数（0=不删除）</summary>
        public int CycleLogRetentionDays { get; set; } = 0;

        /// <summary>原始日志保留天数（0=不删除）</summary>
        public int RawLogRetentionDays { get; set; } = 0;

        /// <summary>日志清理检查间隔（分钟）</summary>
        public int LogCleanupIntervalMinutes { get; set; } = 60;

        /// <summary>服务ID标识</summary>
        [JsonProperty("serviceId")]
        public string ServiceId { get; set; } = "collector-service";

        // ===== 以下为从DB加载的运行时配置 =====

        /// <summary>采集失败重试次数（默认3）</summary>
        [JsonIgnore]
        public int CollectRetryCount { get; set; } = 3;

        /// <summary>采集重试间隔秒数（默认30）</summary>
        [JsonIgnore]
        public int CollectRetryIntervalSeconds { get; set; } = 30;

        /// <summary>连续失败N次触发告警（默认5）</summary>
        [JsonIgnore]
        public int CollectFailAlertThreshold { get; set; } = 5;

        /// <summary>
        /// 从文件加载配置
        /// </summary>
        public static CollectorConfig Load()
        {
            // 优先从运行目录读取
            string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "collector.json");
            if (!File.Exists(configPath))
            {
                // 开发模式：从项目根目录读取
                configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "collector.json");
            }
            if (!File.Exists(configPath))
            {
                throw new FileNotFoundException("找不到配置文件 collector.json");
            }

            string json = File.ReadAllText(configPath);
            return JsonConvert.DeserializeObject<CollectorConfig>(json);
        }
    }
}
