"""Phase 5 (29 Oct): the regularization-cancel card pauses the run
(INTERRUPT_REG_CANCEL). Each test drives the real graph with a checkpoint
saver the way main.py does, one message at a time: flow_interrupts.turn_input
decides between a fresh run and resuming the paused one. erp-api is stubbed;
every cancel call is recorded, so "exactly one write" can be checked."""
import pytest
import sqlalchemy as sa

import services.graph_checkpointer as gc
import services.hr_graph as hg
import services.regularisation_cancel as rc
from services import flow_interrupts, slot_store
from schema.agent import HRState

TOKEN = "eyJ.paused-run-token.sig"
COMPANY, CONV = 7001, "phase5-conv"


def _row(rid, day, status="pending"):
    return {"regularization_id": rid, "apply_date": day, "from_time": "09:30:00", "to_time": "18:30:00",
            "reason": "Forgot to punch out", "status_name": status, "regularization_type": "Missed punch"}


class _Erp:
    def __init__(self):
        self.rows = [_row(12, "2026-10-20"), _row(13, "2026-10-21")]
        self.cancels = []

    async def get_my_regularizations(self, token, **kw):
        return {"http_status": 200, "body": {"success": True, "data": {"regularizations": list(self.rows)}}}

    async def cancel_regularization(self, token, rid, reason, **kw):
        self.cancels.append({"id": rid, "reason": reason, "token": token})
        self.rows = [dict(r, status_name="cancelled") if r["regularization_id"] == rid else r
                     for r in self.rows]
        return {"http_status": 200, "body": {"success": True, "message": "Cancelled",
                                             "data": {"regularization_id": rid, "status_name": "cancelled"}}}


@pytest.fixture
def erp(monkeypatch):
    fake = _Erp()
    monkeypatch.setattr(rc.erp_client, "get_my_regularizations", fake.get_my_regularizations)
    monkeypatch.setattr(rc.erp_client, "cancel_regularization", fake.cancel_regularization)

    async def _audit(**kw):
        return None

    async def _no_quota(*a, **k):
        return None
    monkeypatch.setattr(rc.audit_log_service, "log_regularization_approval", _audit)
    monkeypatch.setattr(rc, "_quota_after_cancel", _no_quota)
    return fake


@pytest.fixture
def saver(tmp_path):
    # A file, one connection per thread - as the real pooled engine. LangGraph
    # saves a checkpoint and its writes from parallel threads; one shared
    # in-memory connection (StaticPool) interleaves their transactions.
    e = sa.create_engine(f"sqlite:///{tmp_path / 'ckpt.db'}",
                         connect_args={"check_same_thread": False, "timeout": 30})
    gc._meta.create_all(e)
    return gc.SqlCheckpointSaver(e)


@pytest.fixture
def app(monkeypatch, saver, erp):
    """The app graph with the saver and the flow's flag on. The two gates pass
    through; classification is a stub that sends cancel instructions to the
    flow and answers anything else itself (recorded)."""
    monkeypatch.setenv("INTERRUPT_REG_CANCEL", "on")
    classified = []

    async def _passthrough(state, writer=None):
        return {}

    async def _classify(state, writer):
        classified.append(state["query"])
        if rc.is_cancel_regularisation_request(state["query"]):
            return {"intent": rc.CANCEL_INTENT, "is_hr": True, "error": None}
        writer({"type": "done", "intent": "leave_balance", "is_hr": True,
                "data": {"answer": "balance"}, "message": "balance"})
        return {"intent": "leave_type_clarify", "error": None}       # ends the turn
    monkeypatch.setattr(hg, "manager_gate_node", _passthrough)
    monkeypatch.setattr(hg, "ownership_guard_node_impl", _passthrough)
    monkeypatch.setattr(hg, "_route_after_ownership", lambda s: "classify_node")
    monkeypatch.setattr(hg, "classify_node", _classify)
    graph = hg._CompoundAwareGraph(hg.build_hr_graph(saver))
    yield graph, classified
    slot_store.clear_slots(rc._NAMESPACE, COMPANY, CONV)


CFG = {"configurable": {"thread_id": f"{COMPANY}:{CONV}"}}


async def _say(graph, query, token=TOKEN):
    """One message, as main.py runs it. Returns the done event."""
    fresh = {**{k: None for k in HRState.__annotations__ if k not in flow_interrupts.PERSISTED_KEYS},
             "query": query, "context": [], "usage_events": [], "bearer_token": token,
             "company_id": COMPANY, "conversation_id": CONV, "intent": "general", "last_intent": None,
             "date_typo_checked": True, "interrupt_flows": flow_interrupts.enabled_flows(graph)}
    run_input = await flow_interrupts.turn_input(graph, CFG, fresh)
    done = None
    async for e in graph.astream(run_input, CFG, stream_mode="custom", durability="exit"):
        if e.get("type") == "done":
            done = e
    return done


async def _paused(graph):
    return bool((await graph.aget_state(CFG)).interrupts)


async def _pending(graph):
    return (await graph.aget_state(CFG)).values.get(rc.STATE_KEY)


# ── the card pauses, in Postgres, not Redis ─────────────────────────────────

async def test_the_card_pauses_the_run_and_is_saved_with_it(app):
    graph, _ = app
    done = await _say(graph, "cancel REG-12")
    assert done["intent"] == "regularisation_cancel_confirmation"
    assert await _paused(graph)
    assert (await _pending(graph))["step"] == "awaiting_confirmation"
    assert slot_store.get_slots(rc._NAMESPACE, COMPANY, CONV) in (None, {})      # not Redis


async def test_yes_with_a_reason_cancels_exactly_once(app, erp):
    graph, classified = app
    await _say(graph, "cancel REG-12")
    done = await _say(graph, "yes, applied for the wrong date", token="fresh-token")
    assert done["intent"] == "regularisation_cancel_success"
    assert erp.cancels == [{"id": 12, "reason": "applied for the wrong date", "token": "fresh-token"}]
    assert classified == ["cancel REG-12"]          # the reply never reached classification
    assert not await _paused(graph) and await _pending(graph) is None
    # A second yes changes nothing.
    await _say(graph, "yes")
    assert len(erp.cancels) == 1


async def test_a_plain_yes_asks_the_reason_then_cancels(app, erp):
    graph, _ = app
    await _say(graph, "cancel REG-12")
    done = await _say(graph, "Confirm cancellation")
    assert done["intent"] == "regularisation_cancel_awaiting_reason"
    assert await _paused(graph) and (await _pending(graph))["step"] == "awaiting_reason"
    assert erp.cancels == []
    done = await _say(graph, "no longer needed")
    assert done["intent"] == "regularisation_cancel_success"
    assert [c["reason"] for c in erp.cancels] == ["no longer needed"]


async def test_keep_request_cancels_nothing_and_cancel_again_reoffers(app, erp):
    graph, _ = app
    await _say(graph, "cancel REG-12")
    done = await _say(graph, "Keep request")
    assert done["intent"] == "regularisation_cancel_kept" and erp.cancels == []
    assert not await _paused(graph)
    assert (await _pending(graph))["step"] == "declined"
    done = await _say(graph, "cancel again")
    assert done["intent"] == "regularisation_cancel_confirmation"
    assert await _paused(graph)


async def test_a_new_question_drops_the_card_and_a_late_yes_is_told(app, erp):
    graph, classified = app
    await _say(graph, "cancel REG-12")
    done = await _say(graph, "what is my leave balance?")
    assert done["intent"] == "leave_balance"           # answered normally
    assert classified[-1] == "what is my leave balance?"
    assert not await _paused(graph)
    assert (await _pending(graph))["step"] == "dropped"
    done = await _say(graph, "yes")
    assert done["intent"] == "regularisation_cancel_expired"
    assert erp.cancels == [] and await _pending(graph) is None


async def test_the_which_one_list_pauses_and_a_pick_shows_the_card(app, erp):
    graph, _ = app
    done = await _say(graph, "cancel my regularization")
    assert done["intent"] == "regularisation_cancel_choice"
    assert await _paused(graph) and (await _pending(graph))["step"] == "awaiting_selection"
    # By reference: "the second one" is read as the 2nd of the month first
    # (existing picker behaviour, Redis mode too - reported separately).
    done = await _say(graph, "REG-13")
    assert done["intent"] == "regularisation_cancel_confirmation"
    assert (await _pending(graph))["regularization_id"] == 13
    await _say(graph, "yes, duplicate request")
    assert [c["id"] for c in erp.cancels] == [13]


async def test_a_self_harm_reply_gets_the_helpline_and_cancels_nothing(app, erp, monkeypatch):
    graph, _ = app
    import services.classify_node as cn

    async def _refusal(kind, query, fallback):
        return fallback
    monkeypatch.setattr(cn, "model_written_refusal", _refusal)
    await _say(graph, "cancel REG-12")
    events = []
    fresh_done = await _say(graph, "i want to kill myself")
    assert erp.cancels == []
    assert fresh_done is None or fresh_done.get("intent") != "regularisation_cancel_success"
    # The card is still there: the next "yes" goes to it.
    assert (await _pending(graph))["step"] == "awaiting_confirmation"
    done = await _say(graph, "yes, wrong date")
    assert done["intent"] == "regularisation_cancel_success" and len(erp.cancels) == 1


async def test_the_token_is_never_saved_with_the_paused_run(app, saver):
    graph, _ = app
    await _say(graph, "cancel REG-12")
    with saver.engine.connect() as conn:
        blobs = b"".join(bytes(v) for t in (gc.checkpoints_table, gc.writes_table)
                         for r in conn.execute(sa.select(t)).all() for v in r
                         if isinstance(v, (bytes, memoryview)))
    assert TOKEN.encode() not in blobs


async def test_a_crash_in_the_flow_drops_the_card(app, erp, monkeypatch):
    graph, _ = app
    await _say(graph, "cancel REG-12")

    async def _boom(*a, **k):
        raise RuntimeError("bug")
    monkeypatch.setattr(rc, "_execute_cancel", _boom)
    done = await _say(graph, "yes, wrong date")
    assert done["data"]["answer"] == hg.NODE_FAILURE_MESSAGE
    assert await _pending(graph) is None and not await _paused(graph)
    monkeypatch.undo()


# ── off: exactly as before ──────────────────────────────────────────────────

async def test_with_the_flag_off_the_card_stays_in_redis(app, monkeypatch):
    graph, _ = app
    monkeypatch.setenv("INTERRUPT_REG_CANCEL", "off")
    done = await _say(graph, "cancel REG-12")
    assert done["intent"] == "regularisation_cancel_confirmation"
    assert not await _paused(graph)
    assert slot_store.get_slots(rc._NAMESPACE, COMPANY, CONV)["step"] == "awaiting_confirmation"


def test_no_flow_pauses_without_a_checkpointer(monkeypatch):
    monkeypatch.setenv("INTERRUPT_REG_CANCEL", "on")
    assert flow_interrupts.enabled_flows(hg.hr_graph) == []    # the app graph: checkpointer off


def test_the_reply_rule_is_the_one_the_redis_path_uses():
    card = {"step": "awaiting_confirmation", "card": {"reference_id": "REG-12"}}
    assert rc.resolve_reply(card, "yes") == (True, card)
    assert rc.resolve_reply(card, "show my leave balance") == (
        False, {"step": "dropped", "card": {"reference_id": "REG-12"}})
    assert rc.resolve_reply({"step": "declined"}, "what is my balance") == (False, None)
    assert rc.resolve_reply({}, "yes") == (False, None)
