# grantflow/tests/test_integration_pilot_public_exports.py

import io

from docx import Document
from fastapi.testclient import TestClient

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

client = TestClient(app)


def test_public_export_payload_downgrades_rfq_readiness_when_ready_annex_file_is_missing():
    job = {
        "status": "done",
        "state": {
            "donor_id": "un_agencies",
            "toc_draft": {
                "proposal_mode": "evaluation_rfq",
                "rfq_profile": "katch_final_assessment",
                "brief": "Final assessment technical response",
                "submission_package_checklist": [
                    {"artifact": "Technical proposal narrative", "owner": "Proposal manager", "status": "ready"}
                ],
                "attachment_manifest": [
                    {
                        "attachment": "Registration certificate",
                        "required_for": "Organization information and legal-status package",
                        "owner": "Operations / compliance",
                        "status": "ready",
                        "source_path": "/tmp/grantflow_missing_annex.pdf",
                    }
                ],
                "compliance_matrix": [
                    {
                        "requirement": "Organization information and legal status package",
                        "response_section": "Organization Information",
                        "evidence": "Registration certificate and audited financials",
                        "status": "ready",
                    }
                ],
            },
            "logframe_draft": {"proposal_mode": "evaluation_rfq", "indicators": []},
            "critic_notes": {"fatal_flaws": [], "quality_score": 8.0, "critic_score": 8.0},
            "citations": [],
        },
    }
    payload = public_job_export_payload("job-rfq-1", job)
    submission_readiness = payload["payload"]["submission_package_readiness"]
    assert submission_readiness["top_gap"] == "attachment_files"
    assert submission_readiness["readiness_status"] == "partial"
    assert float(submission_readiness["completeness_score"]) < 100.0
    assert submission_readiness["attachment_file_validation"]["missing_ready_file_count"] == 1


def test_export_docx_includes_mel_indicator_summary_section():

    gen = client.post(
        "/generate",
        json={
            "donor_id": "usaid",
            "input_context": {"project": "Digital Service Improvement", "country": "Kenya"},
            "llm_mode": False,
            "hitl_enabled": False,
        },
    )
    assert gen.status_code == 200
    job_id = gen.json()["job_id"]
    status = wait_for_terminal_status(client, job_id)
    assert status["status"] == "done"
    state = status["state"]
    indicators = (state.get("logframe_draft") or {}).get("indicators") or []
    assert isinstance(indicators, list) and indicators

    export = client.post("/export", json={"payload": state, "format": "docx"})
    assert export.status_code == 200
    assert export.headers["content-type"].startswith(
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    )

    doc = Document(io.BytesIO(export.content))
    text = "\n".join(p.text for p in doc.paragraphs)
    assert "MEL Indicator Summary" in text
    first_indicator_id = str(indicators[0].get("indicator_id") or "").strip()
    if first_indicator_id:
        assert first_indicator_id in text
    assert "Frequency:" in text
    assert "Data source:" in text
