# grantflow/tests/test_integration_hitl_flows_basic.py

from fastapi.testclient import TestClient


from grantflow.api.app import app

from grantflow.tests.integration_helpers import drain_hitl_to_done, wait_for_terminal_status

client = TestClient(app)


def test_hitl_pause_resume_flow():
    response = client.post(
        "/generate",
        json={
            "donor_id": "usaid",
            "input_context": {"project": "Education", "country": "Kenya"},
            "llm_mode": False,
            "hitl_enabled": True,
        },
    )
    assert response.status_code == 200
    job_id = response.json()["job_id"]

    status = wait_for_terminal_status(client, job_id)
    assert status["status"] == "pending_hitl"
    assert status["checkpoint_stage"] == "toc"
    assert status["state"]["hitl_pending"] is True
    assert status["state"]["toc_draft"]
    assert "logframe_draft" not in status["state"]

    cp_id = status["checkpoint_id"]
    approve = client.post(
        "/hitl/approve",
        json={"checkpoint_id": cp_id, "approved": True, "feedback": "TOC approved"},
    )
    assert approve.status_code == 200

    resume = client.post(f"/resume/{job_id}", json={})
    assert resume.status_code == 200
    assert resume.json()["resuming_from"] == "mel"

    status = wait_for_terminal_status(client, job_id)
    assert status["status"] == "pending_hitl"
    assert status["checkpoint_stage"] == "logframe"
    assert status["state"]["hitl_pending"] is True
    assert status["state"]["logframe_draft"]

    cp_id = status["checkpoint_id"]
    approve = client.post(
        "/hitl/approve",
        json={"checkpoint_id": cp_id, "approved": True, "feedback": "Logframe approved"},
    )
    assert approve.status_code == 200

    resume = client.post(f"/resume/{job_id}", json={})
    assert resume.status_code == 200
    assert resume.json()["resuming_from"] == "critic"

    status = wait_for_terminal_status(client, job_id)
    if status["status"] != "done":
        status = drain_hitl_to_done(client, job_id, initial_status=status)
    assert status["status"] == "done"
    state = status["state"]
    assert state["hitl_pending"] is False
    assert state["toc_draft"]
    assert state["logframe_draft"]
    engine = str((state.get("critic_notes") or {}).get("engine", "") or "")
    assert engine in {"rules", ""} or engine.startswith("rules+llm:")
