# grantflow/tests/test_integration_review_workflow_exports.py

import gzip

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_review_workflow_export_supports_csv_json_and_gzip():
    job_id = "review-workflow-export-job-1"
    runtime_state.JOB_STORE.set(
        job_id,
        {
            "status": "done",
            "state": {
                "critic_notes": {
                    "fatal_flaws": [
                        {
                            "finding_id": "finding-export-1",
                            "code": "TOC_SCHEMA_INVALID",
                            "severity": "high",
                            "section": "toc",
                            "status": "open",
                            "message": "ToC schema mismatch.",
                        },
                        {
                            "finding_id": "finding-export-2",
                            "code": "MEL_BASELINE_MISSING",
                            "severity": "medium",
                            "section": "logframe",
                            "status": "open",
                            "message": "MEL baseline is missing.",
                        },
                    ]
                }
            },
            "review_comments": [
                {
                    "comment_id": "comment-export-1",
                    "ts": "2026-02-27T11:00:00+00:00",
                    "section": "toc",
                    "status": "open",
                    "message": "Need update before submission.",
                    "linked_finding_id": "finding-export-1",
                },
                {
                    "comment_id": "comment-export-2",
                    "ts": "2026-02-27T11:02:00+00:00",
                    "section": "logframe",
                    "status": "resolved",
                    "message": "Baseline evidence added.",
                    "linked_finding_id": "finding-export-2",
                },
            ],
            "job_events": [
                {
                    "event_id": "rwf-exp-1",
                    "ts": "2026-02-27T11:00:00+00:00",
                    "type": "review_comment_added",
                    "comment_id": "comment-export-1",
                    "section": "toc",
                },
                {
                    "event_id": "rwf-exp-2",
                    "ts": "2026-02-27T11:01:00+00:00",
                    "type": "critic_finding_status_changed",
                    "finding_id": "finding-export-1",
                    "status": "acknowledged",
                    "section": "toc",
                    "severity": "high",
                },
                {
                    "event_id": "rwf-exp-3",
                    "ts": "2026-02-27T11:02:00+00:00",
                    "type": "review_comment_added",
                    "comment_id": "comment-export-2",
                    "section": "logframe",
                },
                {
                    "event_id": "rwf-exp-4",
                    "ts": "2026-02-27T11:03:00+00:00",
                    "type": "critic_finding_status_changed",
                    "finding_id": "finding-export-2",
                    "status": "open",
                    "section": "logframe",
                    "severity": "medium",
                },
            ],
        },
    )

    csv_resp = client.get(
        f"/status/{job_id}/review/workflow/export",
        params={
            "finding_id": "finding-export-1",
            "finding_code": "toc_schema_invalid",
            "finding_section": "toc",
            "comment_status": "open",
            "format": "csv",
        },
    )
    assert csv_resp.status_code == 200
    assert csv_resp.headers["content-type"].startswith("text/csv")
    csv_disposition = csv_resp.headers.get("content-disposition", "")
    assert f"grantflow_review_workflow_{job_id}.csv" in csv_disposition
    csv_text = csv_resp.text
    assert csv_text.startswith("field,value\n")
    assert "filters.finding_id,finding-export-1" in csv_text
    assert "filters.finding_code,TOC_SCHEMA_INVALID" in csv_text
    assert "filters.finding_section,toc" in csv_text
    assert "filters.comment_status,open" in csv_text
    assert "summary.finding_count,1" in csv_text

    json_resp = client.get(
        f"/status/{job_id}/review/workflow/export",
        params={"finding_section": "logframe", "format": "json"},
    )
    assert json_resp.status_code == 200
    assert json_resp.headers["content-type"].startswith("application/json")
    json_payload = json_resp.json()
    assert json_payload["filters"]["finding_section"] == "logframe"
    assert {row["finding_id"] for row in json_payload["findings"]} == {"finding-export-2"}
    assert {row["comment_id"] for row in json_payload["comments"]} == {"comment-export-2"}
    assert json_payload["timeline"]
    assert all(
        str(row.get("section") or "").lower() == "logframe"
        or str(row.get("finding_id") or "") == "finding-export-2"
        or str(row.get("comment_id") or "") == "comment-export-2"
        for row in json_payload["timeline"]
    )

    gzip_resp = client.get(
        f"/status/{job_id}/review/workflow/export",
        params={"finding_code": "MEL_BASELINE_MISSING", "format": "json", "gzip": "true"},
    )
    assert gzip_resp.status_code == 200
    assert gzip_resp.headers["content-type"].startswith("application/gzip")
    gzip_disposition = gzip_resp.headers.get("content-disposition", "")
    assert f"grantflow_review_workflow_{job_id}.json.gz" in gzip_disposition
    gzip_payload = json.loads(gzip.decompress(gzip_resp.content).decode("utf-8"))
    assert gzip_payload["filters"]["finding_code"] == "MEL_BASELINE_MISSING"
    assert {row["finding_id"] for row in gzip_payload["findings"]} == {"finding-export-2"}


def test_status_review_workflow_trends_export_supports_csv_json_and_gzip():
    job_id = "review-workflow-trends-export-job-1"
    runtime_state.JOB_STORE.set(
        job_id,
        {
            "status": "done",
            "state": {
                "critic_notes": {
                    "fatal_flaws": [
                        {
                            "finding_id": "finding-wt-exp-1",
                            "code": "TOC_SCHEMA_INVALID",
                            "severity": "high",
                            "section": "toc",
                            "status": "open",
                            "message": "ToC mismatch.",
                            "updated_at": "2026-02-26T11:00:00+00:00",
                        },
                        {
                            "finding_id": "finding-wt-exp-2",
                            "code": "MEL_BASELINE_MISSING",
                            "severity": "medium",
                            "section": "logframe",
                            "status": "acknowledged",
                            "message": "MEL baseline missing.",
                            "updated_at": "2026-02-27T11:00:00+00:00",
                        },
                    ]
                }
            },
            "review_comments": [
                {
                    "comment_id": "comment-wt-exp-1",
                    "ts": "2026-02-26T10:00:00+00:00",
                    "section": "toc",
                    "status": "open",
                    "message": "Needs stronger assumptions.",
                    "linked_finding_id": "finding-wt-exp-1",
                },
                {
                    "comment_id": "comment-wt-exp-2",
                    "ts": "2026-02-27T10:00:00+00:00",
                    "section": "logframe",
                    "status": "resolved",
                    "message": "Resolved in review pass.",
                    "linked_finding_id": "finding-wt-exp-2",
                },
            ],
            "job_events": [
                {
                    "event_id": "rwf-tr-exp-1",
                    "ts": "2026-02-26T10:00:00+00:00",
                    "type": "review_comment_added",
                    "comment_id": "comment-wt-exp-1",
                    "section": "toc",
                },
                {
                    "event_id": "rwf-tr-exp-2",
                    "ts": "2026-02-26T11:00:00+00:00",
                    "type": "critic_finding_status_changed",
                    "finding_id": "finding-wt-exp-1",
                    "status": "open",
                    "section": "toc",
                    "severity": "high",
                },
                {
                    "event_id": "rwf-tr-exp-3",
                    "ts": "2026-02-27T10:00:00+00:00",
                    "type": "review_comment_status_changed",
                    "comment_id": "comment-wt-exp-2",
                    "status": "resolved",
                    "section": "logframe",
                },
                {
                    "event_id": "rwf-tr-exp-4",
                    "ts": "2026-02-27T11:00:00+00:00",
                    "type": "critic_finding_status_changed",
                    "finding_id": "finding-wt-exp-2",
                    "status": "acknowledged",
                    "section": "logframe",
                    "severity": "medium",
                },
            ],
        },
    )

    csv_resp = client.get(
        f"/status/{job_id}/review/workflow/trends/export",
        params={"finding_section": "toc", "overdue_after_hours": 2, "format": "csv"},
    )
    assert csv_resp.status_code == 200
    assert csv_resp.headers["content-type"].startswith("text/csv")
    csv_disposition = csv_resp.headers.get("content-disposition", "")
    assert f"grantflow_review_workflow_trends_{job_id}.csv" in csv_disposition
    csv_text = csv_resp.text
    assert csv_text.startswith("field,value\n")
    assert "filters.finding_section,toc" in csv_text
    assert "filters.overdue_after_hours,2" in csv_text
    assert "total_series[0].bucket,2026-02-26" in csv_text

    json_resp = client.get(
        f"/status/{job_id}/review/workflow/trends/export",
        params={"finding_code": "MEL_BASELINE_MISSING", "overdue_after_hours": 2, "format": "json"},
    )
    assert json_resp.status_code == 200
    assert json_resp.headers["content-type"].startswith("application/json")
    json_payload = json_resp.json()
    assert json_payload["filters"]["finding_code"] == "MEL_BASELINE_MISSING"
    assert json_payload["bucket_count"] == 1
    assert json_payload["timeline_event_count"] == 2

    gzip_resp = client.get(
        f"/status/{job_id}/review/workflow/trends/export",
        params={"overdue_after_hours": 2, "format": "json", "gzip": "true"},
    )
    assert gzip_resp.status_code == 200
    assert gzip_resp.headers["content-type"].startswith("application/gzip")
    gzip_disposition = gzip_resp.headers.get("content-disposition", "")
    assert f"grantflow_review_workflow_trends_{job_id}.json.gz" in gzip_disposition
    gzip_payload = json.loads(gzip.decompress(gzip_resp.content).decode("utf-8"))
    assert gzip_payload["bucket_count"] == 2
    assert gzip_payload["timeline_event_count"] == 4
