# grantflow/tests/test_integration_demo.py

from fastapi.testclient import TestClient

from grantflow.api.app import app

client = TestClient(app)


def test_demo_endpoint_returns_done_status_without_auth():
    response = client.get("/demo/run")
    assert response.status_code == 200
    body = response.json()

    assert body["demo"] is True
    assert body["donor_id"] == "usaid"
    assert body["status"] in {"done", "error"}  # error is acceptable if grounding gate blocks
    assert body["job_id"].startswith("demo_")
    assert isinstance(body["event_count"], int)
    assert body["event_count"] > 0

    quality = body["quality"]
    assert "verdict" in quality
    assert "grounding_verified" in quality
    assert "critic_score" in quality

    assert "note" in body
    assert "next" in body
    assert body["next"]["onboard"] == "POST /agents/onboarding"
    assert body["next"]["generate"] == "POST /generate"


def test_demo_endpoint_returns_unique_job_ids():
    r1 = client.get("/demo/run")
    r2 = client.get("/demo/run")
    assert r1.status_code == 200
    assert r2.status_code == 200
    assert r1.json()["job_id"] != r2.json()["job_id"]


def test_llms_txt_endpoint_returns_plain_text():
    response = client.get("/llms.txt")
    assert response.status_code == 200
    assert response.headers["content-type"].startswith("text/plain")
    text = response.text
    assert text.startswith("# GrantFlow")
    assert "POST /agents/onboarding" in text
    assert "POST /generate" in text
    assert "GET /demo/run" in text


def test_llms_txt_mentions_key_endpoints():
    response = client.get("/llms.txt")
    text = response.text
    required = [
        "POST /ingest/text",
        "POST /generate/preflight",
        "GET /status/{job_id}",
        "POST /hitl/approve",
        "GET /demo",
        "X-API-Key",
        "retryable",
    ]
    for phrase in required:
        assert phrase in text, f"Missing in llms.txt: {phrase!r}"
