using System;
using StandardScene.Signal.Model;

namespace StandardScene.Signal.Logic
{
    /// <summary>
    /// 一条握手点配置的解析结果。参数格式与反编译 <c>SignalStop.SignalParams</c> 一致。
    /// </summary>
    /// <remarks>
    /// <see cref="SignalParams"/> 按分号切成 <see cref="Parts"/>，缺段时 <see cref="Part"/> 返回空串。
    /// 各类型约定：
    /// <list type="bullet">
    /// <item><c>JGControl</c>：机构名;RequestIn|Arrived;[区域-车组-限额-点列表]</item>
    /// <item><c>PointControl</c>：UP1|UP2|Down1|Down2;机构名</item>
    /// <item><c>TimedCharging</c>：最长秒数;上限电量;下限电量</item>
    /// <item><c>RateFlowControl</c>：区域;车组;限额;点1,点2</item>
    /// </list>
    /// </remarks>
    public sealed class SignalStopSpec
    {
        /// <summary>握手类型名，与 Handler 的 <see cref="Is"/> 比较时忽略大小写。</summary>
        public string SignalType { get; init; } = "";

        /// <summary>原始参数串，限流独立类型会整段交给 <see cref="RateFlowHandler"/>。</summary>
        public string SignalParams { get; init; } = "";

        /// <summary>按 ';' 切分，保留空段（与 Split None 一致，方便 Part(n) 按下标取）。</summary>
        public string[] Parts { get; init; } = Array.Empty<string>();

        /// <summary>取第 <paramref name="index"/> 段；越界或 null 返回空串。</summary>
        public string Part(int index)
        {
            if (index < 0 || index >= Parts.Length)
                return "";
            return Parts[index] ?? "";
        }

        /// <summary>从类型名和参数串构造；类型会 Trim，参数保持原样以便日志对照现场 JSON。</summary>
        public static SignalStopSpec Parse(string signalType, string signalParams)
        {
            var type = (signalType ?? "").Trim();
            var raw = signalParams ?? "";
            return new SignalStopSpec
            {
                SignalType = type,
                SignalParams = raw,
                Parts = raw.Split(new[] { ';' }, StringSplitOptions.None)
            };
        }

        /// <summary>从握手点 Model 构造；model 为 null 时返回 null。</summary>
        public static SignalStopSpec From(HandshakePointModel model)
        {
            if (model == null)
                return null;
            return Parse(model.SignalType, model.SignalParams);
        }

        /// <summary>类型名是否匹配（忽略大小写）。</summary>
        public bool Is(string type) =>
            string.Equals(SignalType, type, StringComparison.OrdinalIgnoreCase);
    }
}
