"""L4: propose a small skill change from feedback; promote only after evaluation.

This finite, deliberately tiny fixture is a mechanism demonstration, not evidence
of general organizational learning. Candidate versions are trusted code.
"""
import json
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from common import Skill, World, decide

FEEDBACK = {"case": "Past export failure", "correction": "Engineering triage required"}
# Labels stay out of the proposal prompt. Four held-out cases, including regressions.
HOLDOUT = [("Download export fails", "engineering"),
           ("CSV export broken", "engineering"),
           ("Invoice amount wrong", "billing"), ("Where is my guide?", "support")]


def route(version, text):
    text = text.lower()
    if "invoice" in text:
        return "billing"
    if version == "v2" and "export" in text:
        return "engineering"
    return "support"


def score(version):
    return sum(route(version, text) == label for text, label in HOLDOUT) / len(HOLDOUT)


class State(TypedDict):
    episode_id: str
    candidate: str
    metrics: dict
    promoted: bool


def build(world: World):
    def propose(state):
        skill = decide(Skill, "Choose v1 or v2 using past feedback. v2 adds export triage.",
                       {"feedback": FEEDBACK, "current": world.get("skill", "active", "v1")},
                       {"version": "v2"})
        return {"candidate": skill.version}

    # snippet:start
    def evaluate(state):
        active = world.get("skill", "active", "v1")
        return {"metrics": {"baseline": score(active),
                            "candidate": score(state["candidate"])}}

    def promote(state):
        metrics = state["metrics"]
        accepted = metrics["candidate"] > metrics["baseline"] and metrics["candidate"] == 1.0
        # Both the active pointer and audit record change in one local transaction.
        with world.db:
            if accepted:
                world.db.execute("INSERT OR REPLACE INTO records VALUES (?,?,?)",
                                 ("skill", "active", json.dumps(state["candidate"])))
            world.db.execute("INSERT OR IGNORE INTO records VALUES (?,?,?)",
                             ("evaluation", state["episode_id"], json.dumps(
                                 {"candidate": state["candidate"], **metrics, "promoted": accepted})))
        return {"promoted": accepted}
    # snippet:end

    graph = StateGraph(State)
    graph.add_node("propose", propose)
    graph.add_node("evaluate", evaluate)
    graph.add_node("promote", promote)
    graph.add_edge(START, "propose")
    graph.add_edge("propose", "evaluate")
    graph.add_edge("evaluate", "promote")
    graph.add_edge("promote", END)
    return graph.compile()


if __name__ == "__main__":
    import uuid
    world = World("l4-skills.sqlite")
    print(build(world).invoke({"episode_id": str(uuid.uuid4())}))
    print("Next run uses:", world.get("skill", "active"))
    world.close()
