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

namespace StandardScene.MagCarSimulator
{
    public sealed class MagCarSimVehicleConfig
    {
        public string Name { get; set; } = "AGV";
        public ushort VehicleCode { get; set; } = 1;
        public int ListenPort { get; set; } = 5001;
        public int StartSiteId { get; set; } = 1;
        public int EndSiteId { get; set; } = 2;
        public int IntervalMs { get; set; } = 2000;

        /// <summary>显式环线站点序列（不含回到起点的重复点）。有值时优先于起点/终点寻路。</summary>
        public List<int> LoopSiteIds { get; set; }
    }

    public sealed class MagCarSimConfig
    {
        public string MapPath { get; set; } = "";
        public bool UseTagValueAsNode { get; set; }
        public string ListenAddress { get; set; } = "0.0.0.0";
        public bool LogRawFrames { get; set; }
        public bool LogQueries { get; set; }

        /// <summary>文件日志根目录（相对 exe 或绝对路径），默认 log。</summary>
        public string LogDirectory { get; set; } = "log";

        /// <summary>是否写入 log 目录下的 magcar-sim_yyyyMMdd.log。</summary>
        public bool EnableFileLog { get; set; } = true;

        public int DefaultIntervalMs { get; set; } = 2000;

        /// <summary>同一环线后车相对前车的发车间隔。≤0 时用该车 IntervalMs。</summary>
        public int LaunchStaggerMs { get; set; }

        /// <summary>磁条交管表。空则按地图目录推断 SimpleLite/config/Signal/mag-control-areas.json。</summary>
        public string ControlAreasPath { get; set; }
        public List<MagCarSimVehicleConfig> Vehicles { get; set; } = new List<MagCarSimVehicleConfig>();

        public static string SettingsPath => Path.Combine(AppContext.BaseDirectory, "appsettings.json");

        public static MagCarSimConfig Load(string path = null)
        {
            path ??= SettingsPath;
            if (!File.Exists(path))
            {
                return CreateDefault();
            }

            var json = File.ReadAllText(path);
            var config = JsonConvert.DeserializeObject<MagCarSimConfig>(json) ?? CreateDefault();
            if (config.Vehicles == null || config.Vehicles.Count == 0)
            {
                config.Vehicles = CreateDefault().Vehicles;
            }

            if (config.DefaultIntervalMs <= 0)
            {
                config.DefaultIntervalMs = 2000;
            }

            foreach (var vehicle in config.Vehicles)
            {
                if (vehicle.IntervalMs <= 0)
                {
                    vehicle.IntervalMs = config.DefaultIntervalMs;
                }

                if (string.IsNullOrWhiteSpace(vehicle.Name))
                {
                    vehicle.Name = $"AGV-{vehicle.VehicleCode}";
                }

                if (vehicle.LoopSiteIds != null && vehicle.LoopSiteIds.Count > 0)
                {
                    vehicle.LoopSiteIds = MapPathFinder.NormalizeLoop(vehicle.LoopSiteIds);
                }
            }

            return config;
        }

        public void Save(string path = null)
        {
            path ??= SettingsPath;
            var json = JsonConvert.SerializeObject(this, Formatting.Indented);
            File.WriteAllText(path, json);
        }

        public static MagCarSimConfig CreateDefault()
        {
            return new MagCarSimConfig
            {
                DefaultIntervalMs = 2000,
                Vehicles =
                {
                    new MagCarSimVehicleConfig
                    {
                        Name = "AGV-1",
                        VehicleCode = 1,
                        ListenPort = 5001,
                        StartSiteId = 1,
                        EndSiteId = 6,
                        IntervalMs = 2000
                    }
                }
            };
        }
    }
}
