# grantflow/tests/test_integration_critic.py

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_status_critic_endpoint_returns_typed_payload():
    response = client.post(
        "/generate",
        json={
            "donor_id": "usaid",
            "input_context": {"project": "Maternal Health", "country": "Kenya"},
            "llm_mode": False,
            "hitl_enabled": False,
        },
    )
    assert response.status_code == 200
    job_id = response.json()["job_id"]

    terminal = wait_for_terminal_status(client, job_id)
    assert terminal["status"] == "done"

    critic_resp = client.get(f"/status/{job_id}/critic")
    assert critic_resp.status_code == 200
    body = critic_resp.json()
    assert body["job_id"] == job_id
    assert body["status"] == "done"
    assert isinstance(body["fatal_flaw_count"], int)
    assert isinstance(body["fatal_flaws"], list)
    assert isinstance(body["fatal_flaw_messages"], list)
    assert isinstance(body["rule_check_count"], int)
    assert isinstance(body["rule_checks"], list)
    assert body["rule_check_count"] == len(body["rule_checks"])
    assert body["fatal_flaw_count"] == len(body["fatal_flaws"])
    if body["rule_checks"]:
        check = body["rule_checks"][0]
        assert "code" in check
        assert "status" in check
        assert "section" in check
    if body["fatal_flaws"]:
        flaw = body["fatal_flaws"][0]
        assert "id" in flaw and flaw["id"]
        assert "finding_id" in flaw and flaw["finding_id"]
        assert flaw["id"] == flaw["finding_id"]
        assert flaw.get("status") in {"open", "acknowledged", "resolved"}
        assert "code" in flaw
        assert "severity" in flaw
        assert "section" in flaw
        assert "message" in flaw
