# tests/test_taxonomy.py
import pytest
from pathlib import Path
from core.taxonomy import TaxonomyModel, load_taxonomy, save_taxonomy

def _write_pair(tmp_path, it_lines, en_lines):
    it_file = tmp_path / "tags-it.txt"
    en_file = tmp_path / "tags-en.txt"
    it_file.write_text("\n".join(it_lines) + "\n")
    en_file.write_text("\n".join(en_lines) + "\n")
    return it_file, en_file

def test_load_taxonomy_basic(tmp_path):
    it_f, en_f = _write_pair(tmp_path, ["linux", "vita"], ["linux", "life"])
    model = load_taxonomy(it_f, en_f)
    assert model.it_to_en["linux"] == "linux"
    assert model.it_to_en["vita"] == "life"

def test_load_taxonomy_orphan_it(tmp_path):
    it_f, en_f = _write_pair(tmp_path, ["linux", "vita", "extra"], ["linux", "life"])
    model = load_taxonomy(it_f, en_f)
    assert "extra" in model.orphans_it

def test_load_taxonomy_orphan_en(tmp_path):
    it_f, en_f = _write_pair(tmp_path, ["linux"], ["linux", "extra-en"])
    model = load_taxonomy(it_f, en_f)
    assert "extra-en" in model.orphans_en

def test_save_taxonomy_round_trips(tmp_path):
    it_f, en_f = _write_pair(tmp_path, ["linux"], ["linux"])
    model = load_taxonomy(it_f, en_f)
    model.it_to_en["vita"] = "life"
    save_taxonomy(model, it_f, en_f)
    model2 = load_taxonomy(it_f, en_f)
    assert model2.it_to_en["vita"] == "life"

def test_save_taxonomy_sorted(tmp_path):
    it_f, en_f = _write_pair(tmp_path, [], [])
    from core.taxonomy import TaxonomyModel
    model = TaxonomyModel(it_to_en={"zzz": "zzz", "aaa": "aaa"}, orphans_it=[], orphans_en=[])
    save_taxonomy(model, it_f, en_f)
    lines = it_f.read_text().splitlines()
    assert lines == sorted(lines)
