"""Tests for the FastAPI WebUI server."""

from __future__ import annotations

import pytest
try:
    from fastapi.testclient import TestClient
except ImportError:  # pragma: no cover - optional dependency path
    TestClient = None

from agentbyte.webui.server import AgentbyteWebUIServer

from .helpers import DummyAgent, DummyOrchestrator

pytestmark = pytest.mark.skipif(TestClient is None, reason="fastapi not installed")


def test_health_endpoint() -> None:
    server = AgentbyteWebUIServer()
    client = TestClient(server.create_app())

    response = client.get("/api/health")
    assert response.status_code == 200
    assert response.json()["status"] == "healthy"


def test_entities_endpoint_lists_registered_entities() -> None:
    server = AgentbyteWebUIServer()
    server.registry.register_entity("agent-1", DummyAgent())
    server.registry.register_entity("orch-1", DummyOrchestrator(DummyAgent()))
    client = TestClient(server.create_app())

    response = client.get("/api/entities")
    data = response.json()

    assert response.status_code == 200
    assert len(data) == 2
    assert {item["type"] for item in data} == {"agent", "orchestrator"}


def test_create_and_fetch_session() -> None:
    server = AgentbyteWebUIServer()
    client = TestClient(server.create_app())

    created = client.post(
        "/api/sessions",
        json={"entity_id": "agent-1", "entity_type": "agent"},
    )
    assert created.status_code == 200
    session_id = created.json()["id"]

    fetched = client.get(f"/api/sessions/{session_id}")
    assert fetched.status_code == 200
    assert fetched.json()["metadata"]["entity_id"] == "agent-1"
