"""L5-inspired research sketch, not an implementation of an L5 organization.

A scheduler supplies a snapshot, not a customer-specific investigation question.
The model chooses a question and a permitted inquiry. All effects are local.
"""
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command, interrupt
from common import Finding, Question, World, decide

SNAPSHOT = {"support": [{"id": "T-41", "release": "R-9", "topic": "exports"},
                        {"id": "T-52", "release": "R-9", "topic": "exports"}],
            "releases": [{"id": "R-9", "change": "export service"}]}
EVIDENCE = [{"id": "T-41", "release": "R-9", "account": "A-7", "topic": "exports"},
            {"id": "T-52", "release": "R-9", "account": "A-8", "topic": "exports"},
            {"id": "R-9", "change": "export service"},
            {"id": "A-7", "renewal_in_days": 18}]


class State(TypedDict):
    snapshot: dict
    question: dict
    evidence: list[dict]
    finding: dict
    authorized: bool
    receipt: dict


def supported(finding, evidence, release_id):
    selected = {row["id"]: row for row in evidence if row["id"] in finding["evidence_ids"]}
    # Validate identifiers AND the relevant relationship, not just citation count.
    return (set(selected) == set(finding["evidence_ids"]) and release_id in selected
            and sum(row.get("release") == release_id and row.get("topic") == "exports"
                    for row in selected.values()) >= 2)


def build(world: World, checkpointer=None):
    def notice(state):
        question = decide(Question, "Inspect this snapshot. Choose whether and what to investigate.",
                          {"snapshot": state["snapshot"], "memory": world.records("observation")},
                          {"investigate": True, "release_id": "R-9",
                           "question": "Are export reports linked to the new release?"})
        return {"question": question.model_dump()}

    def investigate(state):
        # Only one permitted read, limited to a release visible in this snapshot.
        release = state["question"]["release_id"]
        visible = {row["id"] for row in state["snapshot"]["releases"]}
        rows = EVIDENCE if release == "R-9" and release in visible else []
        return {"evidence": rows}

    def diagnose(state):
        finding = decide(Finding, "Use evidence to propose an internal investigation or abstain. "
                         "Association does not establish a root cause.",
                         {"question": state["question"], "evidence": state["evidence"]},
                         {"action": "open_investigation", "evidence_ids": ["T-41", "T-52", "R-9"],
                          "summary": "Two export reports reference R-9; investigate a possible link."})
        return {"finding": finding.model_dump()}

    # snippet:start
    def authorize(state):
        finding = state["finding"]
        grounded = supported(finding, state["evidence"], state["question"]["release_id"])
        if not grounded or finding["action"] == "none":
            return {"authorized": False}
        if finding["action"] == "open_investigation":
            return {"authorized": True}  # Delegated: one internal investigation.
        interrupt({"escalation": finding, "reason": "Outside delegated authority"})
        return {"authorized": False}  # A reviewer cannot expand this service's rights.

    def act(state):
        finding = state["finding"]
        if not state["authorized"] or finding["action"] != "open_investigation":
            return {"receipt": {"status": "no_action"}}
        key = state["question"]["release_id"] + ":export-investigation"
        return {"receipt": world.put("investigation", key, finding)}

    def remember(state):
        if state["receipt"].get("status") != "no_action":
            world.put("observation", state["question"]["release_id"],
                      {"sources": state["finding"]["evidence_ids"],
                       "status": "hypothesis_open", "root_cause_confirmed": False})
        return {}
    # snippet:end

    graph = StateGraph(State)
    for name, node in [("notice", notice), ("investigate", investigate), ("diagnose", diagnose),
                       ("authorize", authorize), ("act", act), ("remember", remember)]:
        graph.add_node(name, node)
    graph.add_edge(START, "notice")
    graph.add_conditional_edges("notice", lambda s: "investigate" if s["question"]["investigate"] else END)
    for source, target in [("investigate", "diagnose"), ("diagnose", "authorize"),
                           ("authorize", "act"), ("act", "remember"), ("remember", END)]:
        graph.add_edge(source, target)
    return graph.compile(checkpointer=checkpointer or InMemorySaver())


if __name__ == "__main__":
    world = World("l5-memory.sqlite")
    # A production scheduler would provide scoped evidence; it is not supplied here.
    config = {"configurable": {"thread_id": "snapshot-demo"}, "recursion_limit": 12}
    result = build(world).invoke({"snapshot": SNAPSHOT}, config)
    print(result)
    world.close()
