using OpenAuth.Repository.Domain;
using System.Text.Json.Nodes;

namespace OpenAuth.WebApi.Model.mqtt
{
    public class HmsAlarmParser
    {
        private readonly JsonObject _hmsMessages;
        private readonly string _getway;
        public HmsAlarmParser(string hmsJsonPath, string getway)
        {
            string json = File.ReadAllText(hmsJsonPath);
            _hmsMessages = JsonNode.Parse(json)?.AsObject() ?? throw new Exception("hms.json 格式错误");
            _getway = getway;
        }

        public List<LasaManageDeviceHms> ParseAlarmMessages(string rawJson)
        {
            List<LasaManageDeviceHms> result = new List<LasaManageDeviceHms>();
            var root = JsonNode.Parse(rawJson)?.AsObject();
            if (root == null)
            {
                return null;
            }

            string method = root["method"]?.ToString() ?? "";
            string bid = root["bid"]?.ToString() ?? "";
            string tid = root["tid"]?.ToString() ?? "";
            if (method != "hms")
            {
                return null;
            }

            var alarmList = root["data"]?["list"]?.AsArray();
            if (alarmList == null || alarmList.Count == 0)
            {
                return null;
            }

            foreach (var alarmItem in alarmList)
            {
                string code = alarmItem?["code"]?.ToString() ?? "";
                int module = alarmItem?["module"]?.GetValue<int>() ?? -1;
                int inTheSky = alarmItem?["in_the_sky"]?.GetValue<int>() ?? 0;

                var args = alarmItem["args"]?.AsObject() ?? new JsonObject();
                int sensorIndex = args["sensor_index"]?.GetValue<int>() ?? 0;
                int componentIndex = args["component_index"]?.GetValue<int>() ?? 0;
                int level = alarmItem?["level"]?.GetValue<int>() ?? 0;

                // 拼接 key
                string key = module switch
                {
                    3 => $"dock_tip_{code}",
                    0 => inTheSky == 1 ? $"fpv_tip_{code}_in_the_sky" : $"fpv_tip_{code}",
                    _ => $"fpv_tip_{code}"
                };

                if (!_hmsMessages.TryGetPropertyValue(key, out var node))
                {
                    continue;
                }

                string zh = node["zh"]?.ToString() ?? "未提供中文文案";
                string en = node["en"]?.ToString() ?? "No English message provided";

                zh = ReplacePlaceholders(zh, code, sensorIndex, componentIndex);
                en = ReplacePlaceholders(en, code, sensorIndex, componentIndex);

                result.Add(new LasaManageDeviceHms
                {
                    Id = Guid.NewGuid().ToString(),
                    BId = bid,
                    TId = tid,
                    Level = level,
                    Sn = _getway,
                    Module = module,
                    CreateTime = DateTime.Now,
                    MessageEn = en,
                    MessageZh = zh,
                    IsResolved = 0,
                    Code = code
                });
            }

            return result;
        }

        private string ReplacePlaceholders(string template, string code, int sensorIndex, int componentIndex)
        {
            return template
                .Replace("%alarmid", code)
                .Replace("%index", (sensorIndex + 1).ToString())
                .Replace("%component_index", Math.Clamp(componentIndex + 1, 1, 2).ToString())
                .Replace("%battery_index", sensorIndex == 0 ? "左" : "右")
                .Replace("%dock_cover_index", sensorIndex == 0 ? "左" : "右")
                .Replace("%charging_rod_index", sensorIndex switch
                {
                    0 => "前",
                    1 => "后",
                    2 => "左",
                    3 => "右",
                    _ => "未知"
                });
        }
    }
}
