using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text.Json;

namespace Metin2Launcher.Localization;

/// <summary>
/// Tiny flat key-value localization loader. Resources are embedded JSON dictionaries.
/// Lookup falls back: requested locale -> en -> the key itself.
/// </summary>
public static class Loc
{
    private static readonly Dictionary<string, Dictionary<string, string>> _bundles = new();
    private static string _current = "cs";

    public static event Action? Changed;

    public static string Current => _current;

    public static IReadOnlyList<string> Available => new[] { "cs", "en" };

    static Loc()
    {
        Load("cs");
        Load("en");
    }

    private static void Load(string locale)
    {
        var asm = typeof(Loc).Assembly;
        var resName = $"Metin2Launcher.Localization.{locale}.json";
        using var s = asm.GetManifestResourceStream(resName);
        if (s is null)
        {
            _bundles[locale] = new Dictionary<string, string>();
            return;
        }
        using var sr = new StreamReader(s);
        var json = sr.ReadToEnd();
        var dict = JsonSerializer.Deserialize<Dictionary<string, string>>(json)
                   ?? new Dictionary<string, string>();
        _bundles[locale] = dict;
    }

    public static void SetLocale(string locale)
    {
        if (!_bundles.ContainsKey(locale))
            locale = "en";
        if (_current == locale) return;
        _current = locale;
        Changed?.Invoke();
    }

    public static string Get(string key)
    {
        if (_bundles.TryGetValue(_current, out var d) && d.TryGetValue(key, out var v))
            return v;
        if (_bundles.TryGetValue("en", out var en) && en.TryGetValue(key, out var ev))
            return ev;
        return key;
    }

    public static string Get(string key, params object?[] args)
    {
        var fmt = Get(key);
        try { return string.Format(fmt, args); }
        catch { return fmt; }
    }
}
