"""Phase 5 (29 Oct): confirmation cards that pause the run (LangGraph interrupt).

A flow that shows a card and waits for the reply (a confirm, a reason, a pick)
pauses there: its waiting card is kept in the graph state, which the
checkpointer (services/graph_checkpointer) saves in Postgres with the paused
run - not in Redis, where it was lost on Live. On the next message, before the
run starts, main.py asks the flow whether the message answers the card, by the
flow's own rules:

  * it does   -> the paused run resumes: the safety step first, then straight
                 back to the flow (no other route can take the reply);
  * it doesn't-> a normal fresh run (which discards the pause); the flow
                 decides what is remembered (e.g. "dropped", so a late "yes" is
                 told the card is gone rather than read as anything else).

A card that is remembered but no longer paused (after a refusal, or "Keep
request") is answered the same way, through a fresh run sent to the flow.

One flow at a time, each behind its own flag, and only with the checkpointer
on. Off, a flow keeps its Redis state and classify_node's routing, unchanged.

Flows: regularization cancel (INTERRUPT_REG_CANCEL).
"""
from __future__ import annotations

import logging
import os
from typing import Optional

from langgraph.types import Command, interrupt

from services import regularisation_cancel

logger = logging.getLogger(__name__)

# name -> the flow's flag, its graph node, the state key holding its waiting
# card, the steps at which it pauses, and its "does this reply answer the
# card?" rule: resolve(pending, query) -> (answers, pending_after).
FLOWS = {
    regularisation_cancel.FLOW_NAME: {
        "flag": "INTERRUPT_REG_CANCEL",
        "node": "regularisation_cancel_node",
        "wait": "regularisation_cancel_wait",
        "key": regularisation_cancel.STATE_KEY,
        "paused_steps": regularisation_cancel.AWAITING_STEPS,
        "resolve": regularisation_cancel.resolve_reply,
    },
}

#: State keys main.py's per-turn reset leaves alone: they carry a flow's
#: waiting card from one message to the next.
PERSISTED_KEYS = frozenset(f["key"] for f in FLOWS.values())


def _flag_on(name: str) -> bool:
    return os.getenv(name, "off").strip().lower() in ("on", "true", "1", "yes")


def enabled_flows(graph) -> list:
    """The flows that pause this turn: flag on, and the graph saves its state
    (no checkpointer, nothing could be resumed)."""
    if getattr(graph, "checkpointer", None) is None:
        return []
    return [name for name, flow in FLOWS.items() if _flag_on(flow["flag"])]


def make_wait_node(name: str):
    """The node a flow goes to after showing its card: pauses the run. On
    resume, the reply becomes this turn's query, marked for the flow."""
    async def _wait(state: dict) -> dict:
        pending = state.get(FLOWS[name]["key"]) or {}
        reply = interrupt({"flow": name, "step": pending.get("step")})
        return {"query": reply, "resumed_flow": name}
    _wait.__name__ = f"{name}_wait"
    return _wait


def route_after_flow(name: str, end):
    """After the flow's node: to its wait node while the card waits on a
    reply and the flow pauses this turn; otherwise the turn ends."""
    def _route(state: dict) -> str:
        pending = state.get(FLOWS[name]["key"]) or {}
        if (name in (state.get("interrupt_flows") or []) and not state.get("error")
                and pending.get("step") in FLOWS[name]["paused_steps"]):
            return FLOWS[name]["wait"]
        return end
    return _route


async def turn_input(graph, config: dict, fresh: dict):
    """What to run for this message: `fresh` (the per-turn state), the same
    with the flow's card updated / the turn sent to the flow, or a
    Command resuming the paused run."""
    flows = fresh.get("interrupt_flows") or []
    if not flows:
        return fresh
    snapshot = await graph.aget_state(config)
    values = snapshot.values or {}
    paused = {i.value.get("flow") for i in (snapshot.interrupts or ())
              if isinstance(getattr(i, "value", None), dict)}
    for name in flows:
        flow = FLOWS[name]
        pending = values.get(flow["key"])
        if not pending:
            continue
        answers, after = flow["resolve"](pending, fresh.get("query") or "")
        if not answers:
            logger.info("[Flow] %s: %r is not a reply to the card - a fresh run", name,
                        (fresh.get("query") or "")[:60])
            return {**fresh, flow["key"]: after}
        if name in paused:
            logger.info("[Flow] %s: resuming the paused run with %r", name, (fresh.get("query") or "")[:60])
            return Command(resume=fresh.get("query") or "", update={**fresh, flow["key"]: after})
        logger.info("[Flow] %s: reply to a remembered card - to the flow", name)
        return {**fresh, flow["key"]: after, "resumed_flow": name}
    return fresh


def is_resume(run_input) -> bool:
    return isinstance(run_input, Command)


def flow_of(state: dict) -> Optional[str]:
    """The flow a passed safety check hands the turn to, if any."""
    name = state.get("resumed_flow")
    return name if name in FLOWS else None
