from grantflow.core.config import config
from grantflow.memory_bank.vector_store import vector_store
from grantflow.tests.integration_generation_grounding_helpers import client, empty_vector_query, stub_generate_preflight
from grantflow.tests.integration_helpers import wait_for_terminal_status


def test_strict_grounding_gate_blocks_job_finalization(monkeypatch):
    monkeypatch.setattr(config.graph, "grounding_gate_mode", "strict")
    stub_generate_preflight(monkeypatch, mode="strict")
    monkeypatch.setattr(vector_store, "query", empty_vector_query)

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

    terminal = wait_for_terminal_status(client, job_id)
    assert terminal["status"] == "error"
    assert "Grounding gate (strict) blocked finalization" in str(terminal.get("error") or "")
    state = terminal.get("state") or {}
    gate = state.get("grounding_gate") or {}
    assert gate.get("mode") == "strict"
    assert gate.get("blocking") is True
    assert gate.get("passed") is False
