using ClaudeDo.Localization;

namespace ClaudeDo.Localization.Tests;

public class LocalizerTests
{
    private static LocaleStore TwoLangStore()
    {
        var dir = Path.Combine(Path.GetTempPath(), "loc_" + Guid.NewGuid().ToString("N"));
        Directory.CreateDirectory(dir);
        File.WriteAllText(Path.Combine(dir, "en.json"),
            """{ "metadata": { "code": "en", "name": "English" }, "settings": { "save": "Save" }, "msg": { "count": "{0} items" } }""");
        File.WriteAllText(Path.Combine(dir, "de.json"),
            """{ "metadata": { "code": "de", "name": "Deutsch" }, "settings": { "save": "Speichern" } }""");
        return LocaleStore.Load(dir);
    }

    [Fact]
    public void Indexer_returns_active_language_value()
    {
        var loc = new Localizer(TwoLangStore(), "de", fallbackCode: "en");
        Assert.Equal("Speichern", loc["settings.save"]);
    }

    [Fact]
    public void Indexer_falls_back_to_english_then_key()
    {
        var loc = new Localizer(TwoLangStore(), "de", fallbackCode: "en");
        Assert.Equal("{0} items", loc["msg.count"]);
        Assert.Equal("nope.missing", loc["nope.missing"]);
    }

    [Fact]
    public void Get_formats_arguments()
    {
        var loc = new Localizer(TwoLangStore(), "en", fallbackCode: "en");
        Assert.Equal("3 items", loc.Get("msg.count", 3));
    }

    [Fact]
    public void SetLanguage_raises_change_and_switches_values()
    {
        var loc = new Localizer(TwoLangStore(), "en", fallbackCode: "en");
        var raised = 0;
        loc.LanguageChanged += (_, _) => raised++;
        loc.SetLanguage("de");
        Assert.Equal("de", loc.CurrentCode);
        Assert.Equal("Speichern", loc["settings.save"]);
        Assert.Equal(1, raised);
    }

    [Fact]
    public void AvailableLanguages_lists_code_and_name()
    {
        var loc = new Localizer(TwoLangStore(), "en", fallbackCode: "en");
        Assert.Contains(loc.AvailableLanguages, l => l.Code == "de" && l.Name == "Deutsch");
    }
}
