using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Newtonsoft.Json.Linq;

namespace StandardScene.MagCarSimulator
{
    /// <summary>读取 mag-control-areas.json，收集触发点与管控区站点。</summary>
    public static class MagControlAreaFile
    {
        private static readonly char[] SiteSeparators = { ',', ';', '|', ' ', '\t' };

        public static HashSet<int> LoadSiteIds(string path)
        {
            var ids = new HashSet<int>();
            if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
            {
                return ids;
            }

            var root = JToken.Parse(File.ReadAllText(path));
            if (root is not JArray rows)
            {
                return ids;
            }

            foreach (var row in rows)
            {
                if (row is not JObject obj)
                {
                    continue;
                }

                if (obj.Value<bool?>("IsUse") == false)
                {
                    continue;
                }

                AddIfPositive(ids, obj.Value<int?>("TriggerSit") ?? 0);
                foreach (var part in (obj.Value<string>("ControlArea") ?? "").Split(SiteSeparators, StringSplitOptions.RemoveEmptyEntries))
                {
                    if (int.TryParse(part.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var id))
                    {
                        AddIfPositive(ids, id);
                    }
                }
            }

            return ids;
        }

        public static string GuessPath(string mapPath, string configuredPath)
        {
            if (!string.IsNullOrWhiteSpace(configuredPath) && File.Exists(configuredPath))
            {
                return Path.GetFullPath(configuredPath);
            }

            if (string.IsNullOrWhiteSpace(mapPath))
            {
                return configuredPath;
            }

            var mapDir = Path.GetDirectoryName(Path.GetFullPath(mapPath));
            if (string.IsNullOrWhiteSpace(mapDir))
            {
                return configuredPath;
            }

            var guessed = Path.GetFullPath(Path.Combine(mapDir, "..", "config", "Signal", "mag-control-areas.json"));
            return File.Exists(guessed) ? guessed : configuredPath;
        }

        private static void AddIfPositive(HashSet<int> ids, int id)
        {
            if (id > 0)
            {
                ids.Add(id);
            }
        }
    }
}
