"""Web console route tests."""

from pathlib import Path

from httpx import ASGITransport, AsyncClient

from app.config import Settings
from app.main import create_app
from tests.unit.test_health import FakeDatabase

_BUNDLED = Path(
    "contracts/e61a893e996d05d376579226e7dfbedbcfce8b71787adacffbc557e6e35901c1/snapshot.json"
)


async def test_root_console_is_served() -> None:
    app = create_app(database_factory=lambda _settings: FakeDatabase(True), worker_factories=())
    async with app.router.lifespan_context(app):
        async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
            response = await client.get("/")
    assert response.status_code == 200
    assert "VMware API Emulator" in response.text
    assert "vmware" in response.text
    assert 'id="catalog-drawer"' in response.text
    assert "catalog-drawer" in response.text
    assert 'id="help-drawer"' in response.text
    assert 'id="help-badge"' in response.text
    assert 'id="data-badge"' in response.text
    assert 'id="data-drawer"' in response.text
    assert "data-badge-btn" in response.text
    assert 'id="endpoints-badge-count"' in response.text
    assert 'id="endpoints-drawer-count"' in response.text
    assert 'id="ui-modal"' in response.text
    assert 'role="alertdialog"' in response.text
    assert "Request body" in response.text


async def test_ui_method_vm_is_implemented() -> None:
    app = create_app(
        settings=Settings(enable_pve_stub=False),
        database_factory=lambda _settings: FakeDatabase(True),
        worker_factories=(),
    )
    async with app.router.lifespan_context(app):
        async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
            method = await client.get(
                "/ui/api/method",
                params={"major": 9, "path": "/api/vcenter/vm", "verb": "GET"},
            )
            assert method.status_code == 200
            assert method.json()["implemented"] is True
            detail = await client.get(
                "/ui/api/method",
                params={"major": 9, "path": "/api/vcenter/vm/{vm}", "verb": "GET"},
            )
            assert detail.status_code == 200
            assert detail.json()["path_fields"][0]["name"] == "vm"


async def test_demo_api_requires_database() -> None:
    app = create_app(database_factory=lambda _settings: FakeDatabase(True), worker_factories=())
    async with app.router.lifespan_context(app):
        async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
            state = await client.get("/ui/api/demo/state")
            load = await client.post("/ui/api/demo/load")
    assert state.status_code == 503
    assert load.status_code == 503


async def test_ui_versions_and_catalog_endpoints() -> None:
    app = create_app(
        settings=Settings(enable_pve_stub=False),
        database_factory=lambda _settings: FakeDatabase(True),
        worker_factories=(),
    )
    async with app.router.lifespan_context(app):
        async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
            versions = await client.get("/ui/api/versions")
            assert versions.status_code == 200
            body = versions.json()
            assert body["plane"] == "vsphere-rest"
            assert {item["major"] for item in body["majors"]} == {6, 7, 8, 9}
            catalog = await client.get("/ui/api/catalog", params={"major": 9})
            assert catalog.status_code == 200
            assert catalog.json()["source_version"] == "8.0.2"
            method = await client.get(
                "/ui/api/method",
                params={"major": 9, "path": "/api/session", "verb": "POST"},
            )
            assert method.status_code == 200
            assert method.json()["implemented"] is True
            compat9 = await client.get("/ui/api/compatibility", params={"major": 9})
            assert compat9.status_code == 200
            c9 = compat9.json()
            assert c9["levels"]["implemented"]["count"] == c9["total_declared"]
            assert c9["levels"]["implemented"]["score"] == 1.0
            compat6 = await client.get("/ui/api/compatibility", params={"major": 6})
            c6 = compat6.json()
            assert c6["levels"]["implemented"]["count"] < c6["total_declared"]
            assert 0 < c6["levels"]["implemented"]["score"] < 1


async def test_pve_stub_plane_still_optional() -> None:
    if not _BUNDLED.is_file():
        return
    settings = Settings(enable_pve_stub=True, contract_snapshot=_BUNDLED)
    app = create_app(
        settings=settings,
        database_factory=lambda _settings: FakeDatabase(True),
        worker_factories=(),
    )
    async with app.router.lifespan_context(app):
        async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
            method = await client.get(
                "/ui/api/method",
                params={"major": 7, "path": "/nodes", "verb": "GET"},
            )
            assert method.status_code == 200
            assert method.json()["implemented"] is True
