import io
import json
import zipfile
from pathlib import Path

from fastapi.testclient import TestClient

from grantflow.api.app import app
from grantflow.tests.pilot_exports_rfq_annex_helpers import base_toc_draft, export_both_zip

client = TestClient(app)


def test_export_both_zip_stages_real_evaluation_rfq_annex_files(tmp_path: Path):
    registration = tmp_path / "registration_certificate.pdf"
    registration.write_bytes(b"%PDF-1.4\nreal annex content\n")

    export = export_both_zip(client, base_toc_draft(source_path=str(registration)))

    assert export.status_code == 200
    with zipfile.ZipFile(io.BytesIO(export.content)) as archive:
        names = set(archive.namelist())
        staged_path = "submission_package/99_attachment_manifest/files/01_registration_certificate.pdf"
        assert staged_path in names
        assert archive.read(staged_path) == b"%PDF-1.4\nreal annex content\n"
        placeholder = archive.read("submission_package/99_attachment_manifest/01_registration_certificate.md").decode(
            "utf-8"
        )
        assert f"- Source path: `{registration}`" in placeholder


def test_export_both_zip_flags_ready_annex_rows_without_real_files():
    missing_path = "/tmp/grantflow_missing_registration_certificate.pdf"
    export = export_both_zip(client, base_toc_draft(source_path=missing_path))

    assert export.status_code == 200
    with zipfile.ZipFile(io.BytesIO(export.content)) as archive:
        names = set(archive.namelist())
        assert "submission_package/99_attachment_manifest/files/01_registration_certificate.pdf" not in names
        manifest = json.loads(archive.read("annex_packer/annex_manifest.json").decode("utf-8"))
        validation = manifest["attachment_file_validation"]
        assert validation["attached_file_count"] == 0
        assert validation["missing_ready_file_count"] == 1
        assert validation["status_file_mismatch_count"] == 0
        row = manifest["attachment_manifest"][0]
        assert row["attachment_file_status"] == "missing"
        assert row["attachment_file_warning"] == "status_ready_but_file_missing"
        summary = archive.read("annex_packer/submission_readiness.md").decode("utf-8")
        assert "## Attachment File Validation" in summary
        assert "Ready rows missing files: `1`" in summary
        assert "warning=`status_ready_but_file_missing`" in summary
