"""Model listing, server-side download, active-model selection."""


def test_list_models(client, auth_headers):
    r = client.get("/v1/models", headers=auth_headers)
    assert r.status_code == 200
    data = r.json()["data"]
    ids = {m["id"] for m in data}
    assert ids == {"base", "small", "medium", "large-v3-turbo"}
    small = next(m for m in data if m["id"] == "small")
    assert small["downloaded"] is True and small["loaded"] is True


def test_list_requires_auth(client):
    assert client.get("/v1/models").status_code == 401


def test_download_unknown_tier_404(client, auth_headers):
    assert client.post("/v1/models/xxl/download",
                       headers=auth_headers).status_code == 404


def test_download_already_present(client, auth_headers):
    r = client.post("/v1/models/small/download", headers=auth_headers)
    assert r.status_code == 200
    assert r.json()["status"] == "already_present"


def test_download_triggers(client, auth_headers, fake_engine):
    import time
    r = client.post("/v1/models/medium/download", headers=auth_headers)
    assert r.status_code == 200
    assert r.json()["status"] == "downloading"
    # background task completes on the loop
    for _ in range(40):
        if "medium" in fake_engine.download_calls:
            break
        time.sleep(0.02)
    assert "medium" in fake_engine.download_calls


def test_select_switches_active(client, auth_headers, fake_engine):
    fake_engine._downloaded.add("medium")
    r = client.post("/v1/models/medium/select", headers=auth_headers)
    assert r.status_code == 200
    assert r.json()["status"] == "active"
    assert "medium" in fake_engine.switch_calls


def test_select_unknown_404(client, auth_headers):
    assert client.post("/v1/models/xxl/select",
                       headers=auth_headers).status_code == 404
