using System.Text.Json;
using ExperionCrawler.Core.Application.Interfaces;
using ExperionCrawler.Core.Domain.Entities;
using Microsoft.Extensions.Logging;

namespace ExperionCrawler.Infrastructure.OpcUa;

/// <summary>
/// 원본 Program.cs 의 LoadStatusCodes() / _statusCodeMap 을 서비스로 분리.
/// statuscode.json 에서 로드하며 Hex 키(대소문자 무시)로 조회한다.
/// </summary>
public class ExperionStatusCodeService : IExperionStatusCodeService
{
    private readonly Dictionary<string, ExperionStatusCodeInfo> _map
        = new(StringComparer.OrdinalIgnoreCase);
    private readonly ILogger<ExperionStatusCodeService> _logger;

    public int LoadedCount => _map.Count;

    public ExperionStatusCodeService(ILogger<ExperionStatusCodeService> logger)
    {
        _logger = logger;
        Load();
    }

    private void Load()
    {
        var path = Path.Combine(Directory.GetCurrentDirectory(), "statuscode.json");
        if (!File.Exists(path)) return;
        try
        {
            var json = File.ReadAllText(path);
            var opts = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
            var list = JsonSerializer.Deserialize<List<ExperionStatusCodeInfo>>(json, opts);
            if (list == null) return;
            foreach (var item in list) _map[item.Hex] = item;
            _logger.LogInformation("✅ {Count}개의 에러 코드 정의 로드 완료.", _map.Count);
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "statuscode.json 로드 실패");
        }
    }

    public ExperionStatusCodeInfo? GetByHex(string hexCode)
        => _map.TryGetValue(hexCode, out var info) ? info : null;

    public ExperionStatusCodeInfo? GetByUint(uint statusCode)
        => GetByHex($"0x{statusCode:X8}");
}
