# grantflow/tests/test_integration_portfolio_filters.py

from fastapi.testclient import TestClient


from grantflow.api import runtime_state

from grantflow.api.app import app

client = TestClient(app)


def test_portfolio_filters_accept_legacy_state_donor_alias():
    runtime_state.JOB_STORE.set(
        "portfolio-legacy-donor-job",
        {
            "status": "done",
            "hitl_enabled": False,
            "state": {
                "donor": "LEGACY_TEST_DONOR",
                "quality_score": 7.0,
                "critic_score": 7.0,
                "needs_revision": False,
            },
            "job_events": [
                {
                    "event_id": "legacy1",
                    "ts": "2026-02-25T10:00:00+00:00",
                    "type": "status_changed",
                    "to_status": "done",
                }
            ],
        },
    )

    metrics = client.get("/portfolio/metrics", params={"donor_id": "legacy_test_donor"})
    assert metrics.status_code == 200
    metrics_body = metrics.json()
    assert metrics_body["filters"]["donor_id"] == "legacy_test_donor"
    assert metrics_body["job_count"] >= 1
    assert int(metrics_body["donor_counts"].get("legacy_test_donor") or 0) >= 1

    quality = client.get("/portfolio/quality", params={"donor_id": "legacy_test_donor"})
    assert quality.status_code == 200
    quality_body = quality.json()
    assert quality_body["filters"]["donor_id"] == "legacy_test_donor"
    assert quality_body["job_count"] >= 1
    assert int(quality_body["donor_counts"].get("legacy_test_donor") or 0) >= 1
