"""VITON13 SCHOOL: a deterministic teaching loop, without a model or network."""
import json

CATALOGUE = {
    "ai": {"title": "Applied AI", "topics": ["goals", "tools", "checks"]},
    "design": {"title": "Design", "topics": ["brief", "prototype", "review"]},
}


def lookup(key):
    if not isinstance(key, str) or not 0 < len(key) <= 32:
        raise ValueError("key must be a string of 1-32 characters")
    return CATALOGUE.get(key)


TOOLS = {"lookup": lookup}


def plan(state):
    """A simulator: replace this proposal function to study model integration."""
    if not state["observations"]:
        return {"type": "tool", "name": "lookup", "args": {"key": state["key"]}}
    return {"type": "final", "answer": state["observations"][-1]["result"]}


def run(key, planner=plan, max_steps=3):
    if type(max_steps) is not int or max_steps < 1:
        raise ValueError("max_steps must be a positive integer")
    state = {"key": key, "observations": []}
    for _ in range(max_steps):
        action = planner(state)
        if not isinstance(action, dict):
            raise ValueError("proposal must be an object")
        if action.get("type") == "final":
            if not state["observations"]:
                raise ValueError("final result requires an observation")
            result = state["observations"][-1]["result"]
            if action.get("answer") != result:
                raise ValueError("final answer must match the retrieved record")
            return {
                "status": "done" if result is not None else "unknown",
                "answer": result, "trace": state["observations"],
            }
        if action.get("type") != "tool" or action.get("name") not in TOOLS:
            raise ValueError("tool is not allowed")
        args = action.get("args")
        if not isinstance(args, dict) or set(args) != {"key"}:
            raise ValueError("lookup requires exactly one key argument")
        if args["key"] != state["key"]:
            raise ValueError("lookup is outside the requested key")
        result = TOOLS[action["name"]](**args)
        state["observations"].append({
            "tool": action["name"], "input": dict(args), "result": result,
        })
    return {"status": "stopped", "answer": None, "trace": state["observations"]}


if __name__ == "__main__":
    print(json.dumps(run("ai"), indent=2))
