"""Real LangGraph workflow mechanics; deterministic nodes, no LLM/API calls."""
import argparse
import json
import operator
import os
from pathlib import Path
import sys
from typing import Annotated, Literal, TypedDict

os.environ["LANGSMITH_TRACING"] = "false"
os.environ["LANGCHAIN_TRACING_V2"] = "false"

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.errors import GraphRecursionError
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt
from pydantic import BaseModel, ConfigDict, Field, ValidationError

ROOT = Path(__file__).resolve().parent


class Request(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    request_id: str = Field(pattern=r"^demo_[a-z0-9_]+$", min_length=6, max_length=48)
    intent: Literal["faq", "change", "unknown"]
    topic: Literal["hours", "price", "missing"]


class Decision(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    decision: Literal["close", "keep_for_human"]


class State(TypedDict, total=False):
    request: dict
    route: str
    evidence: dict | None
    review_ok: bool
    reason: str
    answer: str | None
    status: str
    path: Annotated[list[str], operator.add]


def read_knowledge():
    return json.loads((ROOT / "knowledge.json").read_text(encoding="utf-8"))


def router(state):
    route = "research" if state["request"]["intent"] == "faq" else "human"
    return {"route": route, "reason": "needs_lookup" if route == "research" else "not_read_only_faq",
            "path": ["router"]}


def researcher(state):
    evidence = read_knowledge().get(state["request"]["topic"])
    return {"evidence": evidence, "path": ["research"]}


def reviewer(state):
    expected = read_knowledge().get(state["request"]["topic"])
    evidence = state.get("evidence")
    valid = bool(expected) and evidence == expected
    return {"review_ok": valid, "reason": "source_match" if valid else "missing_or_mismatched_source",
            "path": ["reviewer"]}


def human(state):
    # This node restarts on resume. No write or send occurs before interrupt.
    value = interrupt({"request_id": state["request"]["request_id"], "reason": state["reason"],
                       "allowed_decisions": ["close", "keep_for_human"], "external_action": False})
    decision = Decision.model_validate(value).decision
    return {"status": "closed_without_action" if decision == "close" else "needs_human",
            "answer": None, "path": ["human"]}


def finish(state):
    if state.get("review_ok") and state["request"]["intent"] == "faq":
        return {"answer": state["evidence"]["text"], "status": "completed_local",
                "path": ["finish"]}
    return {"answer": None, "path": ["finish"]}


def build_graph(force_cycle=False):
    workflow = StateGraph(State)
    workflow.add_node("router", router)
    workflow.add_node("research", researcher)
    workflow.add_node("reviewer", reviewer)
    workflow.add_node("human", human)
    workflow.add_node("finish", finish)
    workflow.add_edge(START, "router")
    workflow.add_conditional_edges("router", lambda state: state["route"],
                                   {"research": "research", "human": "human"})
    workflow.add_edge("research", "reviewer")
    workflow.add_conditional_edges("reviewer", lambda state: "research" if force_cycle else (
        "finish" if state["review_ok"] else "human"),
        {"research": "research", "finish": "finish", "human": "human"})
    workflow.add_edge("human", "finish")
    workflow.add_edge("finish", END)
    return workflow.compile(checkpointer=InMemorySaver())


def config(request_id, limit=12):
    if not isinstance(request_id, str) or not request_id.startswith("demo_"):
        raise ValueError("invalid_demo_thread")
    if type(limit) is not int or not 1 <= limit <= 50:
        raise ValueError("invalid_recursion_limit")
    return {"configurable": {"thread_id": request_id}, "recursion_limit": limit, "callbacks": []}


def start_request(graph, value, limit=12):
    request = Request.model_validate(value)
    cfg = config(request.request_id, limit)
    if graph.get_state(cfg).values:
        raise ValueError("demo_thread_already_used")
    return graph.invoke({"request": request.model_dump(), "path": [], "answer": None,
                         "status": "running_local", "review_ok": False}, cfg)


def resume_request(graph, request_id, value, limit=12):
    decision = Decision.model_validate(value)
    cfg = config(request_id, limit)
    snapshot = graph.get_state(cfg)
    if not any(task.interrupts for task in snapshot.tasks):
        raise ValueError("no_pending_interrupt")
    return graph.invoke(Command(resume=decision.model_dump()), cfg)


def inspect(graph, request_id, limit=12):
    cfg = config(request_id, limit)
    snapshot = graph.get_state(cfg)
    return {"state": snapshot.values, "next": list(snapshot.next),
            "interrupts": [entry.value for task in snapshot.tasks for entry in task.interrupts],
            "checkpoint_count": len(list(graph.get_state_history(cfg))),
            "storage": "in_memory_only", "model_calls": 0, "external_writes": 0,
            "authenticated": False}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("scenario", choices=["faq", "price", "missing", "change", "unknown"])
    parser.add_argument("--decision", choices=["close", "keep_for_human"])
    parser.add_argument("--interactive", action="store_true")
    parser.add_argument("--force-cycle", action="store_true")
    parser.add_argument("--recursion-limit", type=int, default=12)
    args = parser.parse_args()
    request = {"request_id": "demo_" + args.scenario,
               "intent": args.scenario if args.scenario in ("change", "unknown") else "faq",
               "topic": args.scenario if args.scenario in ("price", "missing") else "hours"}
    graph = build_graph(args.force_cycle)
    try:
        start_request(graph, request, args.recursion_limit)
        before = inspect(graph, request["request_id"], args.recursion_limit)
        print(json.dumps({"phase": "after_start", **before}, ensure_ascii=False, indent=2))
        if args.interactive and args.decision:
            raise ValueError("choose_interactive_or_decision")
        choice = args.decision
        if args.interactive:
            if not before["interrupts"]:
                raise ValueError("no_pending_interrupt")
            choice = input("Demo decision (close/keep_for_human): ").strip()
        if choice is not None:
            resume_request(graph, request["request_id"], {"decision": choice}, args.recursion_limit)
            print(json.dumps({"phase": "after_resume", **inspect(graph, request["request_id"], args.recursion_limit)},
                             ensure_ascii=False, indent=2))
    except GraphRecursionError:
        print(json.dumps({"ok": False, "error": "graph_recursion_limit", "partial": inspect(
            graph, request["request_id"], args.recursion_limit)}, ensure_ascii=False, indent=2))
        return 2
    except (ValueError, ValidationError, EOFError):
        print(json.dumps({"ok": False, "error": "invalid_demo_request_or_resume"}))
        return 2
    return 0


if __name__ == "__main__":
    sys.stdout.reconfigure(encoding="utf-8")
    raise SystemExit(main())
