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

    response = client.get(
        "/portfolio/review-workflow/sla/trends",
        params={
            "donor_id": donor,
            "status": "done",
            "hitl_enabled": "true",
            "finding_section": "toc",
            "overdue_after_hours": 12,
        },
    )
    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["job_count"] == 2
    assert body["jobs_with_overdue"] == 2
    assert body["jobs_without_overdue"] == 0
    assert body["overdue_finding_count"] == 2
    assert body["overdue_comment_count"] == 2
    assert body["overdue_total"] == 4
    assert body["unresolved_total"] == 4
    assert body["breach_rate"] == 1.0
    assert body["bucket_count"] == 2
    assert body["time_window_start"] == "2026-02-25"
    assert body["time_window_end"] == "2026-02-26"
    assert body["top_severity"] == "high"
    assert body["top_severity_count"] == 2
    assert body["top_section"] == "toc"
    assert body["top_section_count"] == 4
    assert body["top_donor_id"] == donor
    assert body["top_donor_overdue_count"] == 4
    assert body["donor_overdue_counts"][donor] == 4
    assert body["total_series"] == [
        {"bucket": "2026-02-25", "count": 2},
        {"bucket": "2026-02-26", "count": 2},
    ]
    assert body["severity_series"]["high"] == [{"bucket": "2026-02-25", "count": 2}]
    assert body["severity_series"]["medium"] == [{"bucket": "2026-02-26", "count": 2}]
    assert body["donor_series"][donor] == [
        {"bucket": "2026-02-25", "count": 2},
        {"bucket": "2026-02-26", "count": 2},
    ]
    assert body["job_overdue_counts"]["portfolio-review-workflow-sla-trends-job-1"] == 2
    assert body["job_overdue_counts"]["portfolio-review-workflow-sla-trends-job-2"] == 2


def test_portfolio_review_workflow_sla_trends_export_supports_csv_json_and_gzip():
    donor = "portfolio_review_workflow_sla_trends_export_test_donor"
    runtime_state.JOB_STORE.set(
        "portfolio-review-workflow-sla-trends-export-job-1",
        {
            "status": "done",
            "hitl_enabled": True,
            "state": {
                "donor_id": donor,
                "critic_notes": {
                    "fatal_flaws": [
                        {
                            "finding_id": "prwse-1",
                            "code": "TOC_SCHEMA_INVALID",
                            "severity": "high",
                            "section": "toc",
                            "status": "open",
                            "updated_at": "2026-02-27T10:00:00+00:00",
                            "due_at": "2026-02-25T10:00:00+00:00",
                            "sla_hours": 24,
                        }
                    ]
                },
            },
            "review_comments": [
                {
                    "comment_id": "prwse-comment-1",
                    "ts": "2026-02-27T10:05:00+00:00",
                    "section": "toc",
                    "status": "open",
                    "message": "Review needed.",
                    "linked_finding_id": "prwse-1",
                    "due_at": "2026-02-25T11:00:00+00:00",
                    "sla_hours": 24,
                }
            ],
            "job_events": [
                {
                    "event_id": "prwse-evt-1",
                    "ts": "2026-02-27T10:00:00+00:00",
                    "type": "critic_finding_status_changed",
                    "finding_id": "prwse-1",
                    "status": "open",
                    "section": "toc",
                    "severity": "high",
                },
                {
                    "event_id": "prwse-evt-2",
                    "ts": "2026-02-27T10:05:00+00:00",
                    "type": "review_comment_added",
                    "comment_id": "prwse-comment-1",
                    "section": "toc",
                },
            ],
        },
    )

    csv_resp = client.get(
        "/portfolio/review-workflow/sla/trends/export",
        params={
            "donor_id": donor,
            "status": "done",
            "hitl_enabled": "true",
            "finding_section": "toc",
            "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_trends_{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 "total_series[0].bucket,2026-02-25" in csv_text

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

    gzip_resp = client.get(
        "/portfolio/review-workflow/sla/trends/export",
        params={"donor_id": donor, "overdue_after_hours": 12, "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_trends_{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
