# grantflow/tests/test_integration_quality_grounding_gate.py

from fastapi.testclient import TestClient


from grantflow.api import runtime_state

from grantflow.api.app import app

client = TestClient(app)


def test_status_grounding_gate_endpoint_returns_runtime_and_preflight_policies():
    job_id = "grounding-gate-job-1"
    runtime_state.JOB_STORE.set(
        job_id,
        {
            "status": "error",
            "generate_preflight": {
                "risk_level": "high",
                "grounding_policy": {
                    "mode": "strict",
                    "blocking": True,
                    "go_ahead": False,
                    "summary": "preflight_blocked",
                    "reasons": ["namespace_empty"],
                },
            },
            "state": {
                "donor_id": "usaid",
                "grounded_quality_gate": {
                    "mode": "strict",
                    "applicable": True,
                    "passed": False,
                    "blocking": True,
                    "go_ahead": False,
                    "summary": "non_retrieval_citation_rate_above_max",
                    "reasons": ["non_retrieval_citation_rate_above_max"],
                    "reason_details": [
                        {
                            "code": "non_retrieval_citation_rate_above_max",
                            "message": "Non-retrieval citations exceed allowed maximum rate.",
                            "section": "overall",
                            "observed": 0.5,
                            "threshold": 0.35,
                        },
                        {
                            "code": "section_non_retrieval_citation_rate_above_max",
                            "message": "toc non-retrieval citation rate exceeds allowed maximum.",
                            "section": "toc",
                            "observed": 1.0,
                            "threshold": 0.35,
                        },
                    ],
                    "section_signals": {
                        "toc": {
                            "citation_count": 4,
                            "non_retrieval_citation_count": 4,
                            "retrieval_grounded_citation_count": 0,
                            "non_retrieval_citation_rate": 1.0,
                        },
                        "logframe": {
                            "citation_count": 4,
                            "non_retrieval_citation_count": 0,
                            "retrieval_grounded_citation_count": 4,
                            "non_retrieval_citation_rate": 0.0,
                        },
                    },
                    "failed_sections": ["toc"],
                    "evidence": {
                        "sample_citations_by_section": {
                            "toc": [
                                {
                                    "stage": "architect",
                                    "citation_type": "fallback_namespace",
                                    "statement_path": "development_objectives.0",
                                    "doc_id": "strategy::usaid_ads201::development_objectives.0",
                                }
                            ]
                        },
                        "failed_sections": ["toc"],
                    },
                    "citation_count": 8,
                },
                "mel_grounding_policy": {
                    "mode": "warn",
                    "blocking": False,
                    "passed": True,
                    "summary": "mel_grounding_signals_ok",
                },
            },
        },
    )

    response = client.get(f"/status/{job_id}/grounding-gate")
    assert response.status_code == 200
    body = response.json()
    assert body["job_id"] == job_id
    assert body["status"] == "error"
    runtime_gate = body.get("grounded_gate") or {}
    assert runtime_gate["mode"] == "strict"
    assert runtime_gate["blocking"] is True
    assert runtime_gate["passed"] is False
    assert runtime_gate["citation_count"] == 8
    assert runtime_gate["reasons"] == ["non_retrieval_citation_rate_above_max"]
    assert runtime_gate["reason_details"][0]["code"] == "non_retrieval_citation_rate_above_max"
    assert runtime_gate["section_signals"]["toc"]["non_retrieval_citation_rate"] == 1.0
    assert runtime_gate["failed_sections"] == ["toc"]
    assert runtime_gate["evidence"]["sample_citations_by_section"]["toc"][0]["citation_type"] == "fallback_namespace"
    preflight_gate = body.get("preflight_grounding_policy") or {}
    assert preflight_gate["mode"] == "strict"
    assert preflight_gate["blocking"] is True
    assert preflight_gate["summary"] == "preflight_blocked"
    mel_policy = body.get("mel_grounding_policy") or {}
    assert mel_policy["mode"] == "warn"
    assert mel_policy["passed"] is True
