# grantflow/tests/test_integration_portfolio_sla_summary.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_portfolio_review_workflow_sla_endpoint_aggregates_jobs_and_filters():
    donor = "portfolio_review_workflow_sla_test_donor"
    runtime_state.JOB_STORE.set(
        "portfolio-review-workflow-sla-job-1",
        {
            "status": "done",
            "hitl_enabled": True,
            "generate_preflight": {"warning_level": "medium", "risk_level": "medium"},
            "state": {
                "donor_id": donor,
                "critic_notes": {
                    "fatal_flaws": [
                        {
                            "finding_id": "prw-sla-1",
                            "code": "TOC_SCHEMA_INVALID",
                            "severity": "high",
                            "section": "toc",
                            "status": "open",
                            "updated_at": "2026-02-20T10:00:00+00:00",
                            "due_at": "2026-02-25T10:00:00+00:00",
                            "sla_hours": 24,
                        }
                    ]
                },
            },
            "review_comments": [
                {
                    "comment_id": "prw-sla-comment-1",
                    "ts": "2026-02-27T10:05:00+00:00",
                    "section": "toc",
                    "status": "open",
                    "message": "Need stronger assumptions.",
                    "linked_finding_id": "prw-sla-1",
                    "due_at": "2026-02-25T11:00:00+00:00",
                    "sla_hours": 24,
                }
            ],
            "job_events": [
                {
                    "event_id": "prw-sla-evt-1",
                    "ts": "2026-02-27T10:00:00+00:00",
                    "type": "critic_finding_status_changed",
                    "finding_id": "prw-sla-1",
                    "status": "open",
                    "section": "toc",
                    "severity": "high",
                },
                {
                    "event_id": "prw-sla-evt-2",
                    "ts": "2026-02-27T10:05:00+00:00",
                    "type": "review_comment_added",
                    "comment_id": "prw-sla-comment-1",
                    "section": "toc",
                },
            ],
        },
    )
    runtime_state.JOB_STORE.set(
        "portfolio-review-workflow-sla-job-2",
        {
            "status": "done",
            "hitl_enabled": True,
            "generate_preflight": {"warning_level": "low", "risk_level": "low"},
            "state": {
                "donor_id": donor,
                "critic_notes": {
                    "fatal_flaws": [
                        {
                            "finding_id": "prw-sla-2",
                            "code": "MEL_BASELINE_MISSING",
                            "severity": "medium",
                            "section": "toc",
                            "status": "acknowledged",
                            "acknowledged_at": "2026-02-27T11:00:00+00:00",
                            "due_at": "2026-02-26T10:00:00+00:00",
                            "sla_hours": 72,
                        }
                    ]
                },
            },
            "review_comments": [
                {
                    "comment_id": "prw-sla-comment-2",
                    "ts": "2026-02-27T11:05:00+00:00",
                    "section": "toc",
                    "status": "open",
                    "message": "Need indicator source.",
                    "linked_finding_id": "prw-sla-2",
                    "due_at": "2026-02-26T12:00:00+00:00",
                    "sla_hours": 72,
                }
            ],
            "job_events": [
                {
                    "event_id": "prw-sla-evt-3",
                    "ts": "2026-02-27T11:00:00+00:00",
                    "type": "critic_finding_status_changed",
                    "finding_id": "prw-sla-2",
                    "status": "acknowledged",
                    "section": "toc",
                    "severity": "medium",
                },
                {
                    "event_id": "prw-sla-evt-4",
                    "ts": "2026-02-27T11:05:00+00:00",
                    "type": "review_comment_added",
                    "comment_id": "prw-sla-comment-2",
                    "section": "toc",
                },
            ],
        },
    )
    runtime_state.JOB_STORE.set(
        "portfolio-review-workflow-sla-job-3",
        {
            "status": "error",
            "hitl_enabled": False,
            "state": {"donor_id": donor, "critic_notes": {"fatal_flaws": []}},
            "job_events": [],
        },
    )

    response = client.get(
        "/portfolio/review-workflow/sla",
        params={
            "donor_id": donor,
            "status": "done",
            "hitl_enabled": "true",
            "finding_section": "toc",
            "overdue_after_hours": 12,
            "top_limit": 3,
        },
    )
    assert response.status_code == 200
    body = response.json()
    assert body["filters"]["donor_id"] == donor
    assert body["filters"]["status"] == "done"
    assert body["filters"]["hitl_enabled"] is True
    assert body["filters"]["finding_section"] == "toc"
    assert body["filters"]["overdue_after_hours"] == 12
    assert body["filters"]["top_limit"] == 3
    assert body["job_count"] == 2
    assert body["jobs_with_overdue"] == 2
    assert body["jobs_without_overdue"] == 0
    assert body["overdue_comment_count"] == 2
    assert body["overdue_total"] == 2
    assert body["top_donor_id"] == donor
    assert body["top_donor_overdue_count"] == 2
    assert body["donor_overdue_counts"][donor] == 2
    assert body["job_overdue_counts"]["portfolio-review-workflow-sla-job-1"] == 1
    assert body["job_overdue_counts"]["portfolio-review-workflow-sla-job-2"] == 1
    assert len(body["top_overdue"]) == 2
    assert body["top_overdue"][0]["job_id"] in {
        "portfolio-review-workflow-sla-job-1",
        "portfolio-review-workflow-sla-job-2",
    }
    assert body["top_overdue"][0]["donor_id"] == donor
    assert isinstance(body.get("oldest_overdue"), dict)


def test_portfolio_review_workflow_sla_export_supports_csv_json_and_gzip():
    donor = "portfolio_review_workflow_sla_export_test_donor"
    runtime_state.JOB_STORE.set(
        "portfolio-review-workflow-sla-export-job-1",
        {
            "status": "done",
            "hitl_enabled": True,
            "state": {
                "donor_id": donor,
                "critic_notes": {"fatal_flaws": []},
            },
            "review_comments": [
                {
                    "comment_id": "prw-sla-exp-comment-1",
                    "ts": "2026-02-27T10:05:00+00:00",
                    "section": "toc",
                    "status": "open",
                    "message": "Review needed.",
                    "due_at": "2026-02-25T11:00:00+00:00",
                    "sla_hours": 24,
                }
            ],
            "job_events": [
                {
                    "event_id": "prw-sla-exp-evt-1",
                    "ts": "2026-02-27T10:05:00+00:00",
                    "type": "review_comment_added",
                    "comment_id": "prw-sla-exp-comment-1",
                    "section": "toc",
                },
            ],
        },
    )

    csv_resp = client.get(
        "/portfolio/review-workflow/sla/export",
        params={
            "donor_id": donor,
            "status": "done",
            "hitl_enabled": "true",
            "finding_section": "toc",
            "top_limit": 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_portfolio_review_workflow_sla_{donor}_done_hitl_true.csv" in csv_disposition
    csv_text = csv_resp.text
    assert csv_text.startswith("field,value\n")
    assert f"filters.donor_id,{donor}" in csv_text
    assert "filters.status,done" in csv_text
    assert "filters.hitl_enabled,True" in csv_text
    assert "filters.finding_section,toc" in csv_text
    assert "filters.top_limit,2" in csv_text

    json_resp = client.get(
        "/portfolio/review-workflow/sla/export",
        params={"donor_id": donor, "finding_section": "toc", "top_limit": 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"]["donor_id"] == donor
    assert json_payload["filters"]["finding_section"] == "toc"
    assert json_payload["filters"]["top_limit"] == 2
    assert json_payload["overdue_total"] == 1

    gzip_resp = client.get(
        "/portfolio/review-workflow/sla/export",
        params={"donor_id": donor, "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_portfolio_review_workflow_sla_{donor}.json.gz" in gzip_disposition
    gzip_payload = json.loads(gzip.decompress(gzip_resp.content).decode("utf-8"))
    assert gzip_payload["filters"]["donor_id"] == donor
    assert gzip_payload["overdue_total"] == 1
