using System.Collections.Generic;

namespace Combo
{
    /// <summary>
    /// native 桥接返回字符串的解析器，三端共用一处。
    /// <para>格式："ip4a,ip4b|ip6a,ip6b"——'|' 分隔 IPv4/IPv6 两个地址族，',' 分隔同族内多个 IP；
    /// 某侧为空串 = 该族无结果；整体为 NULL/空串 = 不可用。</para>
    /// </summary>
    internal static class HttpDnsBridgeFormat
    {
        internal static HttpDnsResult Parse(string raw, string domain)
        {
            if (string.IsNullOrEmpty(raw))
                return null;

            var parts = raw.Split('|');
            var result = new HttpDnsResult { Domain = domain };

            if (parts.Length >= 1)
                result.IPv4 = ParseIPList(parts[0]);
            if (parts.Length >= 2)
                result.IPv6 = ParseIPList(parts[1]);

            return (result.IPv4 != null || result.IPv6 != null) ? result : null;
        }

        private static string[] ParseIPList(string csv)
        {
            if (string.IsNullOrEmpty(csv))
                return null;

            var ips = new List<string>();
            foreach (var entry in csv.Split(','))
            {
                var ip = entry.Trim();
                if (ip.Length > 0 && ip != "0")
                    ips.Add(ip);
            }

            return ips.Count > 0 ? ips.ToArray() : null;
        }
    }
}
