from io import BytesIO

from pathlib import Path

from docx import Document
from openpyxl import load_workbook

from grantflow.exporters.excel_builder import build_xlsx_from_logframe
from grantflow.exporters.word_builder import build_docx_from_toc


def test_exporters_support_evaluation_rfq_mode():
    toc_draft = {
        "proposal_mode": "evaluation_rfq",
        "toc": {
            "proposal_mode": "evaluation_rfq",
            "rfq_profile": "katch_final_assessment",
            "brief": "Technical response for an external project performance evaluation.",
            "background_context": "Assignment covers project performance and learning needs.",
            "evaluation_purpose": "Assess outcome-level change and implementation performance.",
            "organization_information": "Registered organization with audited financials and Central Asia operating status.",
            "technical_approach_summary": "Mixed-methods design, document review, sampling, analysis software, risks, and ethics.",
            "sampling_plan": "Stakeholder and beneficiary sampling across project geographies.",
            "analytical_software": ["Qualitative coding software"],
            "ethical_considerations": ["Informed consent", "Confidentiality", "Do no harm"],
            "evaluation_questions": [
                "What changes can be substantiated?",
                "What recommendations should guide follow-on action?",
            ],
            "methodology_overview": "Mixed-methods evaluation design with triangulated evidence review.",
            "methodology_components": [
                {
                    "method": "Outcome Harvesting",
                    "purpose": "Capture substantiated outcome-level change",
                    "respondent_group": "Stakeholders and partners",
                    "evidence_source": "Validated project records",
                }
            ],
            "team_composition": [
                {"role": "Team Lead", "responsibility": "Lead technical quality and client communication"}
            ],
            "evaluation_questions_matrix": [
                {
                    "evaluation_question": "What changes can be substantiated through the evidence base?",
                    "key_methods": ["Outcome Harvesting", "Document Review"],
                    "evidence_sources": ["Outcome stories", "Validated project records"],
                    "reporting_use": "Support findings and recommendations.",
                }
            ],
            "methods_coverage_matrix": [
                {
                    "method": "Outcome Harvesting",
                    "covers_questions": ["What changes can be substantiated through the evidence base?"],
                    "respondent_group": "Stakeholders and implementation partners",
                    "expected_output": "Validated outcome findings for the draft evaluation report",
                }
            ],
            "key_personnel": [
                {
                    "name": "Proposed Team Lead",
                    "role": "Team Lead",
                    "qualifications": "Senior evaluation lead with donor reporting experience",
                    "level_of_effort": "Lead oversight across inception and reporting",
                    "cv_status": "ready",
                }
            ],
            "level_of_effort_summary": "Activity-based person-days by phase and role.",
            "technical_experience_summary": "Comparable evaluation experience in development-sector final assessments.",
            "sample_outputs_summary": "Annexed final evaluation reports from comparable assignments.",
            "financial_summary": "Separate financial companion aligned to staffing, fieldwork, analysis, and reporting.",
            "cost_structure": [
                {
                    "cost_bucket": "Professional fees",
                    "basis": "Person-days by role and phase",
                    "estimate": "LOE matrix and rate card",
                    "notes": "Reconciles to technical work plan",
                }
            ],
            "pricing_assumptions": [
                "Professional fees map to named roles and person-days.",
                "Travel and fieldwork assumptions are stated separately.",
            ],
            "payment_schedule_summary": "Milestone-based invoicing at inception, draft, and final submission.",
            "submission_package_checklist": [
                {
                    "artifact": "Technical proposal narrative",
                    "owner": "Proposal manager",
                    "status": "ready",
                    "notes": "Final reviewer-ready narrative package",
                }
            ],
            "attachment_manifest": [
                {
                    "attachment": "Registration certificate",
                    "required_for": "Organization information and legal-status package",
                    "owner": "Operations / compliance",
                    "status": "ready",
                    "notes": "Attach current registration evidence in PDF format.",
                }
            ],
            "compliance_matrix": [
                {
                    "requirement": "Organization information and legal status package",
                    "response_section": "Organization Information",
                    "evidence": "Registration certificate and audited financials",
                    "status": "ready",
                    "notes": "Attached in annex package",
                }
            ],
            "deliverables": [
                {
                    "deliverable": "Inception Report",
                    "timing": "Week 1",
                    "purpose": "Confirm evaluation matrix and work plan",
                }
            ],
            "deliverables_schedule_table": [
                {
                    "deliverable": "Draft Evaluation Report",
                    "due_window": "Week 4",
                    "owner": "Team Lead / Evaluation Specialist",
                    "dependencies": ["Fieldwork complete", "Qualitative coding completed"],
                    "review_gate": "Technical QA and client review",
                }
            ],
            "workplan_summary": ["Mobilize, validate design, and execute fieldwork."],
            "assumptions_risks": ["Stakeholder access remains available."],
            "annex_readiness": ["CVs", "Registration certificate", "Sample outputs", "LOE matrix"],
        },
    }
    logframe_draft = {
        "proposal_mode": "evaluation_rfq",
        "indicators": [
            {
                "indicator_id": "IND_001",
                "name": "Deliverable milestone: Inception Report",
                "result_level": "output",
                "baseline": "0 deliverables",
                "target": "1 deliverable",
                "frequency": "bi-weekly",
                "formula": "Count of required deliverables completed and accepted against the agreed evaluation work plan",
                "definition": "Tracks whether the inception package is completed with reviewer-ready documentation.",
                "justification": "Maps the deliverable schedule into an evaluation RFQ management indicator.",
                "means_of_verification": "Accepted deliverable package and QA checklist",
                "owner": "Evaluation team lead and operations coordinator",
            }
        ],
    }

    doc = Document(BytesIO(build_docx_from_toc(toc_draft, "un_agencies", logframe_draft=logframe_draft)))
    text = "\n".join(p.text for p in doc.paragraphs)
    assert "Evaluation RFQ Technical Proposal" in text
    assert "Organization Information" in text
    assert "Assignment Background" in text
    assert "Evaluation Purpose" in text
    assert "Analysis and Proposed Approaches / Methodologies" in text
    assert "Sampling Plan" in text
    assert "Personnel and Team Composition" in text
    assert "Key Personnel and CV Readiness" in text
    assert "Senior evaluation lead with donor reporting experience" in text
    assert "CV status: ready" in text
    assert "Financial Proposal Companion" in text
    assert "Indicative Cost Structure" in text
    assert "Pricing Assumptions" in text
    assert "Payment Schedule Summary" in text
    assert "LOE matrix and rate card" in text
    assert "Submission Package Completeness" in text
    assert "Technical proposal narrative" in text
    assert "Owner: Proposal manager" in text
    assert "Status: ready" in text
    assert "Attachment Manifest" in text
    assert "Registration certificate" in text
    assert "Required for: Organization information and legal-status package" in text
    assert "Proposed Level of Effort" in text
    assert "Technical Experience and Past Performance References" in text
    assert "Evaluation Questions Matrix" in text
    assert "What changes can be substantiated through the evidence base?" in text
    assert "Methods: Outcome Harvesting, Document Review" in text
    assert "Methods Coverage Matrix" in text
    assert "Stakeholders and implementation partners" in text
    assert "Procurement Compliance Matrix" in text
    assert "Registration certificate and audited financials" in text
    assert "Workplan & Deliverables" in text
    assert "Deliverables Schedule Table" in text


def test_evaluation_rfq_exporters_surface_missing_ready_annex_files(tmp_path: Path):
    existing_annex = tmp_path / "registration-certificate.pdf"
    existing_annex.write_text("placeholder annex", encoding="utf-8")
    missing_annex = tmp_path / "audited-financials.pdf"
    toc_draft = {
        "proposal_mode": "evaluation_rfq",
        "toc": {
            "proposal_mode": "evaluation_rfq",
            "rfq_profile": "katch_final_assessment",
            "brief": "Technical response for an external project performance evaluation.",
            "organization_information": "Registered organization with audited financials and Central Asia operating status.",
            "evaluation_purpose": "Assess outcome-level change and implementation performance.",
            "methodology_overview": "Mixed-methods evaluation design with triangulated evidence review.",
            "submission_package_checklist": [
                {
                    "artifact": "Technical proposal narrative",
                    "owner": "Proposal manager",
                    "status": "ready",
                    "notes": "Final reviewer-ready narrative package",
                }
            ],
            "attachment_manifest": [
                {
                    "attachment": "Registration certificate",
                    "required_for": "Organization information and legal-status package",
                    "owner": "Operations / compliance",
                    "status": "ready",
                    "notes": "Attach current registration evidence in PDF format.",
                    "source_path": str(existing_annex),
                },
                {
                    "attachment": "Audited financial statement",
                    "required_for": "Organization information and legal-status package",
                    "owner": "Operations / compliance",
                    "status": "ready",
                    "notes": "Attach latest audited financial statement.",
                    "source_path": str(missing_annex),
                },
            ],
            "compliance_matrix": [
                {
                    "requirement": "Organization information and legal status package",
                    "response_section": "Organization Information",
                    "evidence": "Registration certificate and audited financials",
                    "status": "ready",
                    "notes": "Attached in annex package",
                }
            ],
            "deliverables": [
                {
                    "deliverable": "Final Evaluation Report",
                    "timing": "Week 4",
                    "purpose": "Deliver final performance findings and recommendations",
                }
            ],
        },
    }

    doc = Document(BytesIO(build_docx_from_toc(toc_draft, "un_agencies", logframe_draft={"indicators": []})))
    text = "\n".join(p.text for p in doc.paragraphs)
    assert "Submission readiness status: partial" in text
    assert "Top submission gap: attachment_files" in text
    assert "Attachment file validation: attached_files=1 | missing_ready_files=1 | status_file_mismatches=0" in text

    wb = load_workbook(BytesIO(build_xlsx_from_logframe({"indicators": []}, "un_agencies", toc_draft=toc_draft)))
    rows = list(wb["Export Contract"].iter_rows(values_only=True))
    export_contract = {str(name): value for name, value in rows if name}
    assert export_contract["Submission Readiness Status"] == "partial"
    assert export_contract["Top Submission Gap"] == "attachment_files"
    assert export_contract["Attached Annex Files"] == 1
    assert export_contract["Ready Annex Rows Missing Files"] == 1
    assert export_contract["Annex Status/File Mismatches"] == 0
