using System.Collections.Generic;
using System.Linq;

namespace molilian.core
{
    public static class AccountWarningConfigCore
    {
        private static readonly char[] Separators = new[] { '\r', '\n', ',', '，', ';', '；' };

        public static Dictionary<string, List<int>> FilterStats(
            string platform,
            Dictionary<string, List<int>> stats,
            string? ignoredGroups)
        {
            if (stats == null || stats.Count == 0) return stats ?? new Dictionary<string, List<int>>();

            HashSet<string> rules = ParseIgnoredGroups(ignoredGroups);
            if (rules.Count == 0) return stats;

            string normalizedPlatform = NormalizeToken(platform);
            return stats
                .Where(item => !ShouldIgnore(rules, normalizedPlatform, item.Key))
                .ToDictionary(item => item.Key, item => item.Value);
        }

        private static bool ShouldIgnore(HashSet<string> rules, string platform, string groupKey)
        {
            string normalizedGroup = NormalizeToken(groupKey);
            if (string.IsNullOrEmpty(normalizedGroup)) return false;

            return rules.Contains(normalizedGroup) || rules.Contains($"{platform}:{normalizedGroup}");
        }

        private static HashSet<string> ParseIgnoredGroups(string? ignoredGroups)
        {
            if (string.IsNullOrWhiteSpace(ignoredGroups))
            {
                return new HashSet<string>(System.StringComparer.OrdinalIgnoreCase);
            }

            return ignoredGroups
                .Split(Separators, System.StringSplitOptions.RemoveEmptyEntries | System.StringSplitOptions.TrimEntries)
                .Select(NormalizeToken)
                .Where(item => !string.IsNullOrEmpty(item) && !item.StartsWith("#"))
                .ToHashSet(System.StringComparer.OrdinalIgnoreCase);
        }

        private static string NormalizeToken(string? value)
        {
            return string.IsNullOrWhiteSpace(value)
                ? string.Empty
                : value.Trim().ToLowerInvariant();
        }
    }
}
