import copy

import pytest

from tools.i18n.translate_manifest import extract_en_catalog, merge_catalog

MANIFEST = {
    "clips": [
        {"id": "cosmos", "strings": {"en": {
            "detected.star": ["star", "young star"],
            "measure.distance": "≈7,500 ly",
        }}},
    ]
}


def test_extract_pulls_every_en_string():
    cat = extract_en_catalog(MANIFEST)
    assert cat == {"cosmos": {"detected.star": ["star", "young star"], "measure.distance": "≈7,500 ly"}}


def test_merge_writes_lang_and_leaves_en():
    m = copy.deepcopy(MANIFEST)
    cat = {"cosmos": {"detected.star": ["estrella", "estrella joven"], "measure.distance": "≈7.500 al"}}
    merge_catalog(m, "es", cat)
    s = m["clips"][0]["strings"]
    assert s["en"]["measure.distance"] == "≈7,500 ly"   # en untouched
    assert s["es"]["detected.star"] == ["estrella", "estrella joven"]


def test_merge_is_idempotent():
    m = copy.deepcopy(MANIFEST)
    cat = {"cosmos": {"detected.star": ["estrella", "estrella joven"], "measure.distance": "≈7.500 al"}}
    merge_catalog(m, "es", cat)
    once = copy.deepcopy(m)
    merge_catalog(m, "es", cat)
    assert m == once


def test_merge_rejects_tier_length_mismatch():
    m = copy.deepcopy(MANIFEST)
    bad = {"cosmos": {"detected.star": ["estrella"], "measure.distance": "≈7.500 al"}}  # 1 tier vs en's 2
    with pytest.raises(ValueError):
        merge_catalog(m, "es", bad)


def test_merge_rejects_type_mismatch():
    m = copy.deepcopy(MANIFEST)
    bad = {"cosmos": {"detected.star": "estrella", "measure.distance": "≈7.500 al"}}  # str vs en's list
    with pytest.raises(ValueError):
        merge_catalog(m, "es", bad)
