# grantflow/tests/test_integration_hitl_flows_idempotency.py

from fastapi.testclient import TestClient


import grantflow.api.routes.jobs as jobs_routes

from grantflow.api import runtime_state

from grantflow.api.app import app

from grantflow.api.idempotency_store_facade import _update_job

client = TestClient(app)


def test_resume_request_id_is_idempotent(monkeypatch):
    checkpoint_id = runtime_state.hitl_manager.create_checkpoint(
        stage="toc",
        state={"donor_id": "usaid", "input_context": {"project": "Resume idem", "country": "Kenya"}},
        donor_id="usaid",
    )
    runtime_state.hitl_manager.approve(checkpoint_id, "approved")

    job_id = "resume-request-id-job-1"
    runtime_state.JOB_STORE.set(
        job_id,
        {
            "status": "pending_hitl",
            "state": {
                "donor_id": "usaid",
                "input_context": {"project": "Resume idem", "country": "Kenya"},
                "hitl_pending": True,
            },
            "hitl_enabled": True,
            "checkpoint_id": checkpoint_id,
            "checkpoint_stage": "toc",
            "resume_from": "mel",
        },
    )

    monkeypatch.setattr(jobs_routes, "_run_hitl_pipeline", lambda *_args, **_kwargs: None)

    first = client.post(f"/resume/{job_id}", params={"request_id": "rid-resume-1"}, json={})
    assert first.status_code == 200
    first_body = first.json()
    assert first_body["request_id"] == "rid-resume-1"
    assert first_body["resuming_from"] == "mel"
    assert first_body.get("idempotent_replay") is not True

    _update_job(job_id, status="done")

    replay = client.post(f"/resume/{job_id}", params={"request_id": "rid-resume-1"}, json={})
    assert replay.status_code == 200
    replay_body = replay.json()
    assert replay_body["request_id"] == "rid-resume-1"
    assert replay_body["idempotent_replay"] is True
    assert replay_body["resuming_from"] == "mel"

    job = runtime_state.JOB_STORE.get(job_id) or {}
    events = job.get("job_events") if isinstance(job.get("job_events"), list) else []
    resume_events = [row for row in events if isinstance(row, dict) and row.get("type") == "resume_requested"]
    assert len(resume_events) == 1
