from grantflow.api import runtime_state
from grantflow.tests.review_traceability_helpers import client


def test_status_export_payload_endpoint_returns_review_ready_payload():
    job_id = "export-payload-1"
    runtime_state.INGEST_AUDIT_STORE.clear()
    runtime_state.INGEST_AUDIT_STORE.append(
        {
            "event_id": "ing-exp-1",
            "ts": "2026-02-24T09:00:00+00:00",
            "donor_id": "usaid",
            "namespace": "usaid_ads201",
            "filename": "ads.pdf",
            "content_type": "application/pdf",
            "metadata": {"doc_family": "donor_policy", "source_type": "donor_guidance"},
            "result": {"chunks_ingested": 4},
        }
    )
    runtime_state.JOB_STORE.set(
        job_id,
        {
            "status": "done",
            "strict_preflight": True,
            "generate_preflight": {
                "donor_id": "usaid",
                "risk_level": "medium",
                "go_ahead": True,
                "warning_count": 1,
                "warnings": [{"code": "LOW_DOC_COVERAGE", "severity": "medium"}],
            },
            "client_metadata": {
                "demo_generate_preset_key": "usaid_gov_ai_kazakhstan",
                "rag_readiness": {
                    "expected_doc_families": ["donor_policy", "country_context"],
                    "donor_id": "usaid",
                },
            },
            "state": {
                "donor_id": "usaid",
                "toc_draft": {"toc": {"brief": "Sample ToC"}},
                "logframe_draft": {"indicators": [{"indicator_id": "IND_001"}]},
                "citations": [{"stage": "mel", "label": "USAID ADS 201 p.12"}],
                "quality_score": 8.2,
                "critic_score": 7.9,
                "critic_notes": {
                    "fatal_flaws": [
                        {
                            "finding_id": "finding-1",
                            "status": "acknowledged",
                            "severity": "high",
                            "section": "toc",
                            "code": "TOC_SCHEMA_INVALID",
                            "message": "Schema mismatch",
                            "fix_hint": "Fix objective structure",
                            "source": "rules",
                        }
                    ]
                },
                "strategy": object(),
                "donor_strategy": object(),
            },
            "review_comments": [
                {
                    "comment_id": "comment-1",
                    "status": "open",
                    "section": "toc",
                    "message": "Please revise objective hierarchy",
                    "linked_finding_id": "finding-1",
                    "version_id": "toc_v1",
                }
            ],
        },
    )

    response = client.get(f"/status/{job_id}/export-payload")
    assert response.status_code == 200
    body = response.json()
    assert body["job_id"] == job_id
    assert body["status"] == "done"
    payload = body["payload"]
    assert isinstance(payload, dict)
    assert isinstance(payload["state"], dict)
    assert "strategy" not in payload["state"]
    assert "donor_strategy" not in payload["state"]
    assert payload["state"]["toc_draft"]["toc"]["brief"] == "Sample ToC"
    assert payload["quality_summary"]["quality_score"] == 8.2
    assert payload["quality_summary"]["critic_score"] == 7.9
    assert payload["quality_summary"]["fatal_flaw_count"] == 1
    assert payload["quality_summary"]["citation_count"] == 1
    assert isinstance(payload["critic_findings"], list)
    assert payload["critic_findings"][0]["id"] == "finding-1"
    assert payload["critic_findings"][0]["finding_id"] == "finding-1"
    assert payload["critic_findings"][0]["linked_comment_ids"] == ["comment-1"]
    assert isinstance(payload["review_comments"], list)
    assert payload["review_comments"][0]["linked_finding_id"] == "finding-1"
    assert payload["readiness"]["preset_key"] == "usaid_gov_ai_kazakhstan"
    assert payload["readiness"]["expected_doc_families"] == ["donor_policy", "country_context"]
    assert payload["readiness"]["present_doc_families"] == ["donor_policy"]
    assert payload["readiness"]["missing_doc_families"] == ["country_context"]
    assert payload["readiness"]["coverage_rate"] == 0.5
    assert payload["review_readiness_summary"]["open_critic_findings"] == 1
    assert payload["review_readiness_summary"]["open_review_comments"] == 1
    assert payload["review_readiness_summary"]["fallback_strategy_citations"] == 0
    assert payload["architect_citation_signals"]["architect_citation_count"] == 0
    assert payload["architect_citation_signals"]["evidence_signal_count"] == 0
    assert payload["architect_citation_signals"]["review_hint_preview"] == []
    export_contract = payload["export_contract"]
    assert export_contract["template_key"] == "usaid"
    assert export_contract["status"] == "warning"
    assert "missing_required_toc_sections" in (export_contract.get("reasons") or [])
