using System.Text.Json;
using System.Text.Json.Serialization;

namespace Prospect.Server.Api.Services.GameRef;

// One reference entry: readable name, rarity, category. Sourced from community-datamined
// data (TCF-Wiki), bundled as Data/gameref.json. Compact keys n/r/c to keep the file small.
public class GameRefEntry
{
    [JsonPropertyName("n")] public string Name { get; set; } = "";
    [JsonPropertyName("r")] public string Rarity { get; set; } = "";
    [JsonPropertyName("c")] public string Category { get; set; } = "";
}

// Resolves internal item / vanity ids to readable names for the admin back-office.
public class GameRefService
{
    private readonly Dictionary<string, GameRefEntry> _ref = new(StringComparer.OrdinalIgnoreCase);

    public GameRefService(ILogger<GameRefService> logger)
    {
        try
        {
            var path = Path.Combine(AppContext.BaseDirectory, "Data", "gameref.json");
            if (File.Exists(path))
            {
                var data = JsonSerializer.Deserialize<Dictionary<string, GameRefEntry>>(File.ReadAllText(path));
                if (data != null)
                {
                    foreach (var kv in data)
                    {
                        _ref[kv.Key] = kv.Value;
                    }
                }
            }
            logger.LogInformation("GameRef loaded {Count} entries", _ref.Count);
        }
        catch (Exception e)
        {
            logger.LogWarning(e, "GameRef load failed");
        }
    }

    public GameRefEntry? Get(string? id) => id != null && _ref.TryGetValue(id, out var e) ? e : null;

    public string Name(string? id) => Get(id)?.Name ?? id ?? "";

    public IReadOnlyDictionary<string, GameRefEntry> All => _ref;
}
