import json

from fastapi.testclient import TestClient

from grantflow.api import runtime_state
from grantflow.api.app import app

client = TestClient(app)


def test_status_comments_export_endpoint_supports_filters_csv_json_and_gzip():
    job_id = "comments-export-job-1"
    runtime_state.JOB_STORE.set(
        job_id,
        {
            "status": "done",
            "state": {"donor_id": "usaid"},
            "review_comments": [
                {
                    "comment_id": "c-1",
                    "ts": "2026-03-02T10:00:00+00:00",
                    "section": "toc",
                    "status": "open",
                    "message": "Clarify assumptions in outcome chain.",
                    "author": "reviewer-a",
                    "version_id": "toc_v2",
                    "linked_finding_id": "finding-1",
                    "due_at": "2026-03-05T10:00:00+00:00",
                    "sla_hours": 72,
                },
                {
                    "comment_id": "c-2",
                    "ts": "2026-03-02T11:00:00+00:00",
                    "section": "general",
                    "status": "resolved",
                    "message": "Looks good now.",
                    "author": "reviewer-b",
                    "version_id": "toc_v2",
                    "resolved_at": "2026-03-02T12:00:00+00:00",
                },
            ],
        },
    )

    export_csv = client.get(
        f"/status/{job_id}/comments/export",
        params={"format": "csv", "section": "toc", "status": "open", "version_id": "toc_v2"},
    )
    assert export_csv.status_code == 200
    assert "text/csv" in (export_csv.headers.get("content-type") or "")
    assert f"grantflow_comments_{job_id}.csv" in (export_csv.headers.get("content-disposition") or "")
    assert "comment_id,ts,section,status,message,author,version_id" in export_csv.text
    assert "c-1" in export_csv.text
    assert "c-2" not in export_csv.text

    export_json = client.get(
        f"/status/{job_id}/comments/export",
        params={"format": "json", "status": "resolved"},
    )
    assert export_json.status_code == 200
    assert "application/json" in (export_json.headers.get("content-type") or "")
    export_json_body = json.loads(export_json.text)
    assert export_json_body["job_id"] == job_id
    assert export_json_body["comment_count"] == 1
    assert export_json_body["comments"][0]["comment_id"] == "c-2"

    export_csv_gzip = client.get(
        f"/status/{job_id}/comments/export",
        params={"format": "csv", "gzip": "true"},
    )
    assert export_csv_gzip.status_code == 200
    assert "application/gzip" in (export_csv_gzip.headers.get("content-type") or "")
    assert (export_csv_gzip.headers.get("content-disposition") or "").endswith('.csv.gz"')
