"""vSphere catalog hot-swap + compatibility UI (offline ASGI)."""

from __future__ import annotations

from httpx import ASGITransport, AsyncClient

from app.config import Settings
from app.main import create_app
from app.vsphere.contracts.matrix import VERSIONS
from tests.unit.test_health import FakeDatabase


def _app():
    return create_app(
        settings=Settings(),
        database_factory=lambda _settings: FakeDatabase(True),
        worker_factories=(),
    )


async def test_vsphere_contract_apply_swaps_catalog_major() -> None:
    app = _app()
    async with app.router.lifespan_context(app):
        async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
            applied = await client.post("/ui/api/contract/apply", params={"major": 7})
            assert applied.status_code == 200
            payload = applied.json()
            assert payload["ok"] is True
            assert payload["major"] == 7
            assert payload["plane"] == "vsphere-rest"
            assert payload["runtime_version"] == VERSIONS[7]["version"]
            assert payload["method_count"] > 0

            report = await client.get("/ui/api/compatibility", params={"major": 7})
            assert report.status_code == 200
            body = report.json()
            assert body["catalog_version"] == VERSIONS[7]["version"]
            assert body["levels"]["implemented"]["count"] == payload["method_count"]

            restored = await client.post("/ui/api/contract/apply", params={"major": 9})
            assert restored.status_code == 200
            assert restored.json()["runtime_version"] == VERSIONS[9]["version"]


async def test_vsphere_hot_swap_reports_full_registry_at_major_9() -> None:
    app = _app()
    async with app.router.lifespan_context(app):
        async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
            applied = await client.post("/ui/api/contract/apply", params={"major": 9})
            assert applied.status_code == 200
            report = await client.get("/ui/api/compatibility", params={"major": 9})
            assert report.status_code == 200
            body = report.json()
            declared = body["total_declared"]
            assert declared > 0
            assert body["levels"]["implemented"]["count"] == declared
            assert body["plane"] == "vsphere-rest"
