"""download_models tests. No network in CI; we test the 'already present →
skip' short-circuit by faking the expected files, and that main() wires
both ensure_* calls.
"""

from unittest.mock import patch

from backend.app.scripts import download_models as dm


def test_ensure_camie_skips_when_present(tmp_path, monkeypatch):
    """v2 layout (HF Camais03/camie-tagger-v2): the ONNX file is named
    camie-tagger-v2.onnx (not model.onnx) and tags ship inside
    camie-tagger-v2-metadata.json (not selected_tags.csv). Both at root.
    Updated 2026-05-25 after the actual repo layout was confirmed via
    WebFetch — the old assertion pinned the v1 filenames."""
    monkeypatch.setattr(dm, "MODEL_ROOT", tmp_path)
    camie = tmp_path / "camie"
    camie.mkdir(parents=True)
    (camie / "camie-tagger-v2.onnx").write_bytes(b"x")
    (camie / "camie-tagger-v2-metadata.json").write_text("{}")
    with patch.object(dm, "_snapshot") as snap:
        dm.ensure_camie()
        snap.assert_not_called()


def test_ensure_camie_downloads_when_missing(tmp_path, monkeypatch):
    monkeypatch.setattr(dm, "MODEL_ROOT", tmp_path)
    with patch.object(dm, "_snapshot") as snap:
        dm.ensure_camie()
        snap.assert_called_once()


def test_ensure_siglip_skips_when_present(tmp_path, monkeypatch):
    monkeypatch.setattr(dm, "MODEL_ROOT", tmp_path)
    sig = tmp_path / "siglip"
    sig.mkdir(parents=True)
    (sig / "config.json").write_text("{}")
    (sig / "model.safetensors").write_bytes(b"x")
    with patch.object(dm, "_snapshot") as snap:
        dm.ensure_siglip()
        snap.assert_not_called()


def test_main_calls_both(monkeypatch):
    calls = []
    monkeypatch.setattr(dm, "ensure_camie", lambda: calls.append("camie"))
    monkeypatch.setattr(dm, "ensure_siglip", lambda: calls.append("siglip"))
    assert dm.main() == 0
    assert calls == ["camie", "siglip"]
