"""L3: cross-system evidence, proposed action, durable approval, local effect."""
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.types import Command, interrupt
from common import Plan, World, allowed, cross_context, decide


class State(TypedDict):
    case_id: str
    evidence: dict
    plan: dict
    approved: bool
    receipt: dict


def build(world: World, checkpointer):
    def observe(state):
        if state["case_id"] != "T-41":
            raise ValueError("Demo principal is scoped to T-41")
        return {"evidence": cross_context()}

    def plan(state):
        proposal = decide(Plan, "Propose one internal follow-up using all four sources.",
                          state["evidence"], {"action": "add_account_note",
                          "summary": "Export issue near renewal; billing is paid. Investigate R-9."})
        return {"plan": proposal.model_dump()}

    # snippet:start
    def approve(state):
        if not allowed(state["plan"]):
            return {"approved": False}  # A model cannot grant itself refund rights.
        decision = interrupt({"case": state["case_id"], "proposal": state["plan"]})
        return {"approved": decision is True}

    def execute(state):
        # Re-check policy after resumption, before the side effect.
        if not state["approved"] or not allowed(state["plan"]):
            return {"receipt": {"status": "denied"}}
        key = f'{state["case_id"]}:{state["plan"]["action"]}'
        return {"receipt": world.put("cross_system_action", key, state["plan"])}
    # snippet:end

    graph = StateGraph(State)
    for name, node in [("observe", observe), ("plan", plan),
                       ("approve", approve), ("execute", execute)]:
        graph.add_node(name, node)
    graph.add_edge(START, "observe")
    graph.add_edge("observe", "plan")
    graph.add_edge("plan", "approve")
    graph.add_edge("approve", "execute")
    graph.add_edge("execute", END)
    return graph.compile(checkpointer=checkpointer)


if __name__ == "__main__":
    # Re-running this process uses the same durable thread and action key.
    world = World("l3-records.sqlite")
    with SqliteSaver.from_conn_string("l3-checkpoints.sqlite") as saver:
        app = build(world, saver)
        config = {"configurable": {"thread_id": "case-T-41"}}
        snapshot = app.get_state(config)
        if not snapshot.values:
            app.invoke({"case_id": "T-41"}, config)
        snapshot = app.get_state(config)
        if snapshot.next:
            print("Pending:", snapshot.tasks)
            approved = input("Approve the displayed local action? [y/N] ").strip().lower() == "y"
            app.invoke(Command(resume=approved), config)
        print(app.get_state(config).values.get("receipt"))
    world.close()
