"""HTTP --runtime-api：多 connection 与 invoke（不调 LLM）。"""

from __future__ import annotations

import pytest

pytest.importorskip("fastapi")

from starlette.testclient import TestClient

from aicd.api_serve import create_aicd_serve_app
from aicd.home import init_home


def test_runtime_api_health_and_ping(tmp_path) -> None:
    root, layout, _ = init_home(tmp_path / "h")
    app = create_aicd_serve_app(
        layout=layout,
        home=root,
        api_key=None,
        runtime_api=True,
        max_connections=4,
        skip_setup=True,
        no_plugins=True,
    )
    with TestClient(app) as client:
        h = client.get("/health").json()
        assert h["ok"] is True
        assert h["runtime_api"] is True
        assert "connections" in h
        r = client.post("/v1/connections", json={})
        assert r.status_code == 200
        cid = r.json()["connection_id"]
        assert r.json().get("chat_session_id")
        inv = client.post(
            f"/v1/connections/{cid}/invoke",
            json={"method": "ping", "params": {}},
        )
        assert inv.status_code == 200
        body = inv.json()
        assert body.get("ok") is True
        assert body["result"]["pong"] is True
        d = client.delete(f"/v1/connections/{cid}")
        assert d.status_code == 200


def test_runtime_api_unknown_invoke_connection(tmp_path) -> None:
    root, layout, _ = init_home(tmp_path / "h2")
    app = create_aicd_serve_app(
        layout=layout,
        home=root,
        api_key=None,
        runtime_api=True,
        skip_setup=True,
        no_plugins=True,
    )
    with TestClient(app) as client:
        inv = client.post(
            "/v1/connections/bad-id/invoke",
            json={"method": "ping", "params": {}},
        )
        assert inv.status_code == 200
        body = inv.json()
        assert body.get("ok") is False
        assert body.get("code") == "connection"
