namespace SHH.CameraSdk;

public class ServiceConfig
{
    // ==========================================
    // 1. 基础属性
    // ==========================================
    public int ParentPid { get; private set; }
    
    public string AppId { get; private set; } = "Unknown_01";
    
    public int NumericId { get; private set; } = 1;
    
    public int BasePort { get; private set; } = 5000;
    
    public int MaxPortRange { get; private set; } = 100;
    
    public NetworkMode Mode { get; private set; } = NetworkMode.Passive;
    
    public bool ShouldConnect => Mode == NetworkMode.Active || Mode == NetworkMode.Hybrid;

    public string SeqServerUrl { get; private set; } = string.Empty;

    public string SeqApiKey { get; private set; } = string.Empty;

    /// <summary>
    /// 更新实际端口
    /// </summary>
    /// <param name="port"></param>
    public void UpdateActualPort(int port)
    {
        this.BasePort = port;
    }

    // ==========================================
    // 2. 目标地址列表 (类型变了！)
    // ==========================================

    // ★★★ 修改点：从 List<string> 变为 List<
    // > ★★★
    public List<ServiceEndpoint> VideoEndpoints { get; private set; } = new List<ServiceEndpoint>();
    public List<ServiceEndpoint> CommandEndpoints { get; private set; } = new List<ServiceEndpoint>();

    // ==========================================
    // 3. 工厂方法 (保持不变)
    // ==========================================
    public static ServiceConfig BuildFromArgs(string[] args)
    {
        var config = new ServiceConfig();
        for (int i = 0; i < args.Length; i++)
        {
            var key = args[i].ToLower().Trim();

            // 确保不越界且下一个参数不是 key (防止 value 为空的情况)
            var value = (i + 1 < args.Length && !args[i + 1].StartsWith("--")) ? args[i + 1] : string.Empty;
            bool consumed = !string.IsNullOrEmpty(value);

            switch (key)
            {
                case "--pid": 
                    if (int.TryParse(value, out int pid)) config.ParentPid = pid; 
                    break;
                case "--appid":
                    if (!string.IsNullOrWhiteSpace(value))
                    {
                        config.AppId = value;
                        config.NumericId = ParseIdFromAppId(value);
                    }
                    break;
                case "--uris":
                    if (!string.IsNullOrWhiteSpace(value)) ParseSingleUriConfig(config, value);
                    break;
                case "--mode": if (int.TryParse(value, out int m)) config.Mode = (NetworkMode)m; break;
                case "--ports":
                    ParsePortConfig(config, value);
                    break;
                case "--sequris":
                    config.SeqServerUrl = ParseSeqUri(value);
                    break;
                case "--seqkey":
                    // 去掉可能存在的分号
                    config.SeqApiKey = value.Replace(";", "").Trim();
                    break;
            }
            if (consumed) i++;
        }
        return config;
    }

    /// <summary>
    /// 解析端口配置
    /// </summary>
    /// <param name="config"></param>
    /// <param name="value"></param>
    private static void ParsePortConfig(ServiceConfig config, string value)
    {
        if (!string.IsNullOrWhiteSpace(value) && value.Contains(","))
        {
            var parts = value.Split(',');
            if (parts.Length >= 1 && int.TryParse(parts[0], out int p)) config.BasePort = p;
            if (parts.Length >= 2 && int.TryParse(parts[1], out int r)) config.MaxPortRange = r;
        }
    }

    /// <summary>
    /// 解析 Seq URI
    /// </summary>
    /// <param name="rawValue"></param>
    /// <returns></returns>
    private static string ParseSeqUri(string rawValue)
    {
        // 格式: 172.16.41.241,20026,日志处置中心;
        try
        {
            rawValue = rawValue.Replace("\"", "").TrimEnd(';'); // 清理引号和末尾分号
            var parts = rawValue.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            if (parts.Length >= 2)
            {
                string ip = parts[0].Trim();
                string port = parts[1].Trim();
                // 组装成标准 HTTP 格式
                return $"http://{ip}:{port}";
            }
            return string.Empty;
        }
        catch
        {
            return string.Empty;
        }
    }

    /// <summary>
    /// 从 AppId 中解析 ID
    /// </summary>
    /// <param name="appId"></param>
    /// <returns></returns>
    private static int ParseIdFromAppId(string appId)
    {
        if (string.IsNullOrWhiteSpace(appId)) return 1;
        int lastIdx = appId.LastIndexOf('_');
        if (lastIdx >= 0 && lastIdx < appId.Length - 1)
        {
            if (int.TryParse(appId.Substring(lastIdx + 1), out int id)) return id;
        }
        return 1;
    }

    // ==========================================
    // 4. 解析算法实现 (核心修改)
    // ==========================================
    private static void ParseSingleUriConfig(ServiceConfig config, string rawValue)
    {
        // 【新增】清理可能存在的双引号，防止地址解析失败
        rawValue = rawValue.Replace("\"", "");

        var segments = rawValue.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

        foreach (var segment in segments)
        {
            var parts = segment.Split(',');
            if (parts.Length < 3) continue;

            string ip = parts[0].Trim();
            string portStr = parts[1].Trim();

            // ★★★ 提取第四个字段作为备注 ★★★
            string desc = parts.Length >= 4 ? parts[2].Trim() : "未命名终端";

            if (int.TryParse(portStr, out int port))
            {
                string zmqUri = $"tcp://{ip}:{port}";

                // 构建对象
                var endpoint = new ServiceEndpoint
                {
                    Uri = zmqUri,
                    Description = desc
                };

                // 添加前检查 Uri 是否重复 (备注不参与排重)
                if (!config.VideoEndpoints.Any(e => e.Uri == zmqUri))
                    config.VideoEndpoints.Add(endpoint);
                if (!config.CommandEndpoints.Any(e => e.Uri == zmqUri))
                    config.CommandEndpoints.Add(endpoint);
            }
        }
    }
}

/// <summary>
/// [新增] 端点配置对象，包含地址和备注
/// </summary>
public class ServiceEndpoint
{
    /// <summary>
    /// ZeroMQ 连接地址 (e.g. "tcp://127.0.0.1:6001")
    /// </summary>
    public string Uri { get; set; } = string.Empty;

    /// <summary>
    /// 备注信息 (e.g. "调试机", "大屏")
    /// </summary>
    public string Description { get; set; } = string.Empty;

    /// <summary>
    /// ToString
    /// </summary>
    /// <returns></returns>
    public override string ToString() => $"{Uri} ({Description})";
}