from __future__ import annotations

from fastapi.testclient import TestClient

from backplane_runtime.api import create_app
from backplane_runtime.demo import build_demo_runtime


def test_public_demo_and_health(tmp_path):
    runtime = build_demo_runtime(tmp_path / "state.sqlite3")
    with TestClient(create_app(runtime=runtime)) as client:
        health = client.get("/api/health")
        assert health.status_code == 200
        assert health.json()["backend"]["backend"] == "evidence"

        response = client.post(
            "/api/demo/run",
            json={"tenant": "support", "prompt": "What is the refund window?"},
        )
        assert response.status_code == 200
        body = response.json()
        assert body["receipt"]["tenant_id"] == "support"
        assert body["receipt"]["status"] == "completed"
        assert "30 days" in body["text"]


def test_authenticated_openai_compatible_route(tmp_path):
    runtime = build_demo_runtime(tmp_path / "state.sqlite3")
    key = runtime.create_tenant("customer-a", "Customer A")
    runtime.assign("customer-a", ["policy.support"])
    with TestClient(create_app(runtime=runtime)) as client:
        response = client.post(
            "/v1/chat/completions",
            headers={
                "Authorization": f"Bearer {key}",
                "X-Backplane-Tenant": "customer-a",
            },
            json={
                "model": "backplane",
                "messages": [{"role": "user", "content": "Hello"}],
                "max_tokens": 24,
            },
        )
        assert response.status_code == 200
        body = response.json()
        assert body["object"] == "chat.completion"
        assert body["backplane_receipt"]["tenant_id"] == "customer-a"


def test_management_surface_fails_closed(tmp_path):
    runtime = build_demo_runtime(tmp_path / "state.sqlite3")
    with TestClient(create_app(runtime=runtime, admin_token="admin-secret")) as client:
        assert client.get("/api/admin/status").status_code == 401
        assert (
            client.get(
                "/api/admin/status", headers={"X-Admin-Token": "admin-secret"}
            ).status_code
            == 200
        )


def test_request_size_limit(tmp_path):
    runtime = build_demo_runtime(tmp_path / "state.sqlite3")
    with TestClient(create_app(runtime=runtime)) as client:
        response = client.post(
            "/api/demo/run",
            content=b"x" * 65_537,
            headers={"Content-Type": "application/json"},
        )
        assert response.status_code == 413
        assert "traceback" not in response.text.casefold()


def test_receipt_history_requires_authentication_and_scopes_cursor(tmp_path):
    runtime = build_demo_runtime(tmp_path / "state.sqlite3")
    key = runtime.create_tenant("history-a", "History A")
    runtime.store.save_receipt("history-1", "history-a", {"receipt_id":"history-1"})
    runtime.store.save_receipt("history-other", "support", {"receipt_id":"history-other"})
    headers={"Authorization": f"Bearer {key}", "X-Backplane-Tenant":"history-a"}
    with TestClient(create_app(runtime=runtime)) as client:
        assert client.get("/api/receipts").status_code == 401
        response=client.get("/api/receipts",headers=headers)
        assert response.json()["receipts"] == [{"receipt_id":"history-1"}]
        assert client.get("/api/receipts?before=history-other",headers=headers).status_code == 400
        assert client.get("/api/receipts?limit=201",headers=headers).status_code == 422

