import uuid

from fastapi.testclient import TestClient

from grantflow.api.app import app
from grantflow.tests.integration_helpers import wait_for_terminal_status

client = TestClient(app)


def test_agent_can_self_register_and_run_sandbox_generation_happy_path():
    registration = client.post(
        "/agents/register",
        json={
            "agent_name": "Sandbox Runner",
            "agent_type": "workflow_agent",
            "purpose": "Validate self-serve agent onboarding",
        },
    )
    assert registration.status_code == 200
    registration_body = registration.json()
    assert registration_body["agent_id"] == "agent_sandbox_runner"
    assert registration_body["tenant_id"] == "sandbox_sandbox_runner"

    preflight_payload = registration_body["sample_requests"]["preflight"]
    preflight = client.post("/generate/preflight", json=preflight_payload)
    assert preflight.status_code == 200
    preflight_body = preflight.json()
    assert preflight_body["donor_id"] == "usaid"
    assert preflight_body["architect_rag_enabled"] is False
    assert preflight_body["grounding_policy"]["blocking"] is False

    generate_payload = dict(registration_body["sample_requests"]["generate"])
    generate_payload["request_id"] = f"agent-sandbox-{uuid.uuid4().hex}"
    generate = client.post("/generate", json=generate_payload)
    assert generate.status_code == 200
    generate_body = generate.json()
    assert generate_body["status"] == "accepted"
    assert generate_body["request_id"] == generate_payload["request_id"]

    job_id = generate_body["job_id"]
    terminal = wait_for_terminal_status(client, job_id)
    assert terminal["status"] == "done"
    assert terminal["state"]["tenant_id"] == "sandbox_sandbox_runner"

    quality = client.get(f"/status/{job_id}/quality")
    assert quality.status_code == 200
    quality_body = quality.json()
    assert quality_body["job_id"] == job_id
    assert quality_body["status"] == "done"

    events = client.get(f"/status/{job_id}/events")
    assert events.status_code == 200
    events_body = events.json()
    assert events_body["job_id"] == job_id
    assert events_body["event_count"] >= 1
