"""Integration: seeded Automation API surface returns real DB-backed data."""

from __future__ import annotations

import os

import pytest
from httpx import ASGITransport, AsyncClient

from app.config import Settings
from app.main import create_app
from app.vsphere.seed import seed_vsphere_inventory

pytestmark = pytest.mark.integration


@pytest.fixture
async def client() -> AsyncClient:
    database_url = os.getenv("TEST_DATABASE_URL") or os.getenv("DATABASE_URL")
    if not database_url:
        pytest.skip("TEST_DATABASE_URL / DATABASE_URL required")
    settings = Settings(
        database_url=database_url,  # type: ignore[arg-type]
        contract_snapshot=None,
        enable_pve_stub=False,
    )
    app = create_app(settings=settings, worker_factories=())
    async with app.router.lifespan_context(app):
        await seed_vsphere_inventory(app.state.database, force=True, profile="big")
        async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as http:
            yield http


async def _session(client: AsyncClient) -> dict[str, str]:
    login = await client.post("/api/session", auth=("administrator@vsphere.local", "VMware1!"))
    assert login.status_code == 201, login.text
    return {"vmware-api-session-id": login.json()}


async def test_demo_cluster_api_state_and_inventory(client: AsyncClient) -> None:
    headers = await _session(client)

    vm_list = await client.get("/api/vcenter/vm", headers=headers)
    assert vm_list.status_code == 200
    assert len(vm_list.json()) >= 2000

    hosts = await client.get("/api/vcenter/host", headers=headers)
    assert hosts.status_code == 200
    assert len(hosts.json()) >= 20

    ssh = await client.get("/api/appliance/access/ssh", headers=headers)
    assert ssh.status_code == 200
    assert ssh.json().get("enabled") is True
    assert "stub" not in ssh.json()

    supervisors = await client.get(
        "/api/vcenter/namespace-management/supervisors/supervisor-1/summary",
        headers=headers,
    )
    assert supervisors.status_code == 200
    body = supervisors.json()
    assert isinstance(body, dict)
    assert "stub" not in body
    assert body.get("status") == "ENABLED" or body.get("name") or body.get("id")

    esx = await client.get("/api/esx/settings/clusters/domain-c21/software", headers=headers)
    assert esx.status_code == 200
    assert esx.json().get("status") == "COMPLIANT"
    assert "domain-c21" in (esx.json().get("clusters") or [])

    cdroms = await client.get("/api/vcenter/vm/vm-101/hardware/cdrom", headers=headers)
    assert cdroms.status_code == 200
    assert isinstance(cdroms.json(), list)
    assert cdroms.json()[0]["cdrom"] == "3000"

    libs = await client.get("/api/content/library", headers=headers)
    assert libs.status_code == 200
    assert len(libs.json()) >= 2

    put = await client.put("/api/appliance/access/ssh", headers=headers, json={"enabled": False})
    assert put.status_code in {200, 204}
    if put.status_code == 200:
        assert put.json().get("enabled") is False
    ssh2 = await client.get("/api/appliance/access/ssh", headers=headers)
    assert ssh2.json().get("enabled") is False
    await client.put("/api/appliance/access/ssh", headers=headers, json={"enabled": True})
