# grantflow/tests/test_integration_generation.py

from fastapi.testclient import TestClient

from grantflow.api.app import app
from grantflow.tests.integration_helpers import wait_for_terminal_status

client = TestClient(app)


def test_generate_basic_async_job_flow():
    payload = {
        "donor_id": "usaid",
        "input_context": {"project": "Water Sanitation", "country": "Kenya"},
        "llm_mode": False,
        "hitl_enabled": False,
    }
    response = client.post("/generate", json=payload)
    assert response.status_code == 200
    data = response.json()
    assert data["status"] == "accepted"
    assert "job_id" in data

    status = wait_for_terminal_status(client, data["job_id"])
    assert status["status"] == "done"
    state = status["state"]
    assert state["toc_draft"]
    assert state["logframe_draft"]
    assert state["quality_score"] >= 0
    critic_notes = state.get("critic_notes") or {}
    assert isinstance(critic_notes.get("fatal_flaws"), list)
    if critic_notes.get("fatal_flaws"):
        flaw = critic_notes["fatal_flaws"][0]
        assert isinstance(flaw, dict)
        assert "code" in flaw
        assert "section" in flaw
        assert "message" in flaw
    assert isinstance(critic_notes.get("rule_checks"), list)


def test_generate_llm_mode_false_uses_non_llm_toc_engine():
    payload = {
        "donor_id": "usaid",
        "input_context": {"project": "Public Administration", "country": "Kazakhstan"},
        "llm_mode": False,
        "hitl_enabled": False,
    }
    response = client.post("/generate", json=payload)
    assert response.status_code == 200
    job_id = response.json()["job_id"]

    status = wait_for_terminal_status(client, job_id)
    assert status["status"] == "done"
    state = status["state"]
    generation_meta = state.get("toc_generation_meta") or {}
    assert generation_meta.get("llm_used") is False
    assert str(generation_meta.get("engine") or "").startswith("deterministic:")
    assert generation_meta.get("llm_requested") is False
    assert generation_meta.get("llm_attempted") is False
    assert generation_meta.get("fallback_used") is False
    assert generation_meta.get("fallback_class") == "deterministic_mode"
