from __future__ import annotations

from fastapi import HTTPException

from grantflow.api.export_helpers import _portfolio_export_response


def _csv_renderer(_: dict) -> str:
    return "a,b\n1,2\n"


def test_portfolio_export_response_rejects_unsupported_format() -> None:
    try:
        _portfolio_export_response(
            payload={"items": []},
            filename_prefix="grantflow_demo",
            donor_id=None,
            status=None,
            hitl_enabled=None,
            export_format="xml",
            gzip_enabled=False,
            csv_renderer=_csv_renderer,
        )
    except HTTPException as exc:
        assert exc.status_code == 400
        detail = exc.detail if isinstance(exc.detail, dict) else {}
        assert detail.get("code") == "unsupported_format"
        assert detail.get("retryable") is False
        return
    raise AssertionError("Expected HTTPException for unsupported export format")


def test_portfolio_export_response_csv_headers() -> None:
    response = _portfolio_export_response(
        payload={"items": []},
        filename_prefix="grantflow_demo",
        donor_id="usaid",
        status="done",
        hitl_enabled=True,
        export_format="csv",
        gzip_enabled=False,
        csv_renderer=_csv_renderer,
    )
    assert response.media_type == "text/csv; charset=utf-8"
    assert response.headers["Content-Disposition"].endswith('grantflow_demo_usaid_done_hitl_true.csv"')


def test_portfolio_export_response_json_gzip_headers() -> None:
    response = _portfolio_export_response(
        payload={"items": []},
        filename_prefix="grantflow_demo",
        donor_id=None,
        status=None,
        hitl_enabled=None,
        export_format="json",
        gzip_enabled=True,
        csv_renderer=_csv_renderer,
    )
    assert response.media_type == "application/gzip"
    assert response.headers["Content-Disposition"].endswith('grantflow_demo.json.gz"')
