namespace molilian.core
{
    internal static class ZlongForwardChannels
    {
        public const string LegacyChannel = "xhs";
        public static readonly string[] Supported = new[] { "xhs", "ks", "bili" };

        public static string NormalizeChannel(string channel)
        {
            if (string.IsNullOrWhiteSpace(channel)) return string.Empty;

            string normalized = channel.Trim().ToLowerInvariant();
            return Array.Exists(Supported, item => string.Equals(item, normalized, StringComparison.OrdinalIgnoreCase))
                ? normalized
                : string.Empty;
        }

        public static string[] NormalizeChannels(string channels, bool fallbackToAll = true)
        {
            if (string.IsNullOrWhiteSpace(channels))
            {
                return fallbackToAll ? Supported.ToArray() : Array.Empty<string>();
            }

            var list = new List<string>();
            foreach (var item in channels.Split(',', StringSplitOptions.RemoveEmptyEntries))
            {
                string value = item.Trim();
                if (string.Equals(value, "all", StringComparison.OrdinalIgnoreCase))
                {
                    return Supported.ToArray();
                }

                string normalized = NormalizeChannel(value);
                if (string.IsNullOrEmpty(normalized) || list.Contains(normalized)) continue;

                list.Add(normalized);
            }

            if (list.Count > 0) return list.ToArray();
            return fallbackToAll ? Supported.ToArray() : Array.Empty<string>();
        }

        public static bool IsEnabled(string channels, string channel)
        {
            string normalizedChannel = NormalizeChannel(channel);
            if (string.IsNullOrEmpty(normalizedChannel)) return false;

            return Array.Exists(
                NormalizeChannels(channels, fallbackToAll: false),
                item => string.Equals(item, normalizedChannel, StringComparison.OrdinalIgnoreCase)
            );
        }

        public static int GetSortOrder(string channel)
        {
            string normalizedChannel = NormalizeChannel(channel);
            if (string.IsNullOrEmpty(normalizedChannel)) return Supported.Length;

            int index = Array.IndexOf(Supported, normalizedChannel);
            return index >= 0 ? index : Supported.Length;
        }

        public static bool UsesLegacyKeys(string channel)
        {
            string normalizedChannel = NormalizeChannel(channel);
            return string.Equals(normalizedChannel, LegacyChannel, StringComparison.OrdinalIgnoreCase);
        }
    }
}
