import uuid

from fastapi.testclient import TestClient

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

client = TestClient(app)


def _run_sandbox_job() -> str:
    registration = client.post("/agents/register", json={"agent_name": "Disclosure Runner"})
    body = registration.json()
    client.post("/generate/preflight", json=body["sample_requests"]["preflight"])
    generate_payload = dict(body["sample_requests"]["generate"])
    generate_payload["request_id"] = f"disclosure-{uuid.uuid4().hex}"
    generate = client.post("/generate", json=generate_payload)
    job_id = generate.json()["job_id"]
    wait_for_terminal_status(client, job_id)
    return job_id


def test_ai_disclosure_endpoint_is_honest_for_deterministic_job():
    job_id = _run_sandbox_job()

    response = client.get(f"/status/{job_id}/ai-disclosure")
    assert response.status_code == 200
    body = response.json()

    assert body["job_id"] == job_id
    assert body["ai_assisted"] is True
    # The sandbox sample runs deterministic (llm_mode=false) — no live LLM calls.
    assert body["generation_mode"] == "deterministic"
    assert body["models"] == []
    assert body["human_review"]["required_before_submission"] is True
    assert body["grounding"]["mode"] in {"off", "warn", "strict"}
    # The boundary must say it is a disclosure, not a compliance certification.
    assert any("not a certification" in line.lower() for line in body["boundary"])
    assert "human review is required before submission" in body["human_readable"].lower()


def test_ai_disclosure_payload_reports_models_in_llm_mode():
    job = {
        "status": "done",
        "hitl_enabled": True,
        "state": {"llm_mode": True, "donor_id": "eu"},
    }
    disclosure = public_job_ai_disclosure_payload("job-llm-1", job)

    assert disclosure["generation_mode"] == "llm_assisted"
    assert disclosure["models"]  # at least one configured model identifier
    assert disclosure["human_review"]["hitl_checkpoints_enabled"] is True
