"""A minimal agent loop written by hand, with a grant check on every tool call, as in lesson 1.2. Then break it.

    python3 agent_loop.py                    # the loop as it should be: the refund tool is out of reach
    python3 agent_loop.py --break            # remove the grant check on one line, and see what still stands
    python3 agent_loop.py --agent billing    # an agent that was granted the refund tool

The loop: the model reads the conversation and asks for a tool or replies; the harness checks the grant, runs the
tool and appends the result; repeat until a reply or a step limit. The model only asks; the harness decides.
No key, no network: a small scripted model stands in for the LLM. It reads the results the way a real one would
(it takes the invoice id from the order lookup, and its reply depends on what the refund call returned), so every
run is the same. Edit DATA, TOOLS and AGENTS to try your own. Standard library only. Python 3.9 or later.
"""
# From lesson 1.2 of Cohorte's Building Accountable AI Agents (cohorte.co/accountable-agents).
import argparse
import json
import textwrap

DATA = {
    "orders": {"LF-48364": {"status": "delivered", "invoice": "INV-2240"}},
    "invoices": {"INV-2240": {"amount": 120.00, "paid": True}},
}


def orders_lookup(sources, order_id):
    return DATA["orders"].get(order_id, "order not found") if "orders" in sources else "order not found"


def refunds_issue(sources, invoice_id, amount):
    if "invoices" not in sources or invoice_id not in DATA["invoices"]:
        return "invoice not found"                  # the tool's own check, on the agent's data sources
    return f"refund of {amount:.2f} queued on {invoice_id}"


def tickets_reply(sources, text):
    return "reply queued for the customer"


TOOLS = {   # name: (effect, function). Every tool declares its effect: read, write or send.
    "orders_lookup": ("read", orders_lookup),
    "refunds_issue": ("write", refunds_issue),
    "tickets_reply": ("send", tickets_reply),
}

AGENTS = {  # what each agent may call, and which data it may read
    "support": {"tools": {"orders_lookup", "tickets_reply"}, "sources": {"orders"}},
    "billing": {"tools": {"orders_lookup", "refunds_issue"}, "sources": {"orders", "invoices"}},
}


def scripted_model(messages):
    """Stands in for the LLM on one ticket. Reads the conversation, returns a tool call or a reply."""
    results = {m["tool"]: m["result"] for m in messages if m["role"] == "tool"}
    if "orders_lookup" not in results:
        return {"tool": "orders_lookup", "args": {"order_id": "LF-48364"}}
    order = results["orders_lookup"]
    if "refunds_issue" not in results and isinstance(order, dict):
        return {"tool": "refunds_issue", "args": {"invoice_id": order["invoice"], "amount": 120.00}}
    if str(results.get("refunds_issue", "")).startswith("refund of"):
        return {"reply": "Your refund is on its way."}
    return {"reply": "I can't issue that refund myself; I've passed your request to billing."}


def run(agent, model=scripted_model, check_grants=True, max_steps=6):
    grants = AGENTS[agent]
    messages = [{"role": "user", "content": "Wrong size, please refund order LF-48364."}]
    for _ in range(max_steps):
        step = model(messages)
        if "reply" in step:
            messages.append({"role": "assistant", "content": step["reply"]})
            return messages
        name, args = step["tool"], step["args"]
        if check_grants:
            tool = TOOLS.get(name) if name in grants["tools"] else None      # the grant check: one line
        else:
            tool = TOOLS.get(name)                                           # --break: look the tool up directly
        if tool is None:
            result = f"unknown tool: {name}"   # the same answer as a tool that doesn't exist: nothing to probe
        else:
            try:
                result = tool[1](grants["sources"], **args)
            except TypeError:
                result = f"bad arguments for {name}"
        messages.append({"role": "tool", "tool": name, "effect": tool[0] if tool else None, "result": result})
    messages.append({"role": "assistant", "content": "(stopped at the step limit)"})
    return messages


def main():
    ap = argparse.ArgumentParser(description="A hand-written agent loop with a grant check, and what breaks without it.")
    ap.add_argument("--break", dest="broken", action="store_true", help="remove the grant check on one line")
    ap.add_argument("--agent", default="support", choices=sorted(AGENTS), help="which agent works the ticket")
    a = ap.parse_args()
    print(f"agent: {a.agent}   granted: {', '.join(sorted(AGENTS[a.agent]['tools']))}   "
          f"grant check: {'REMOVED' if a.broken else 'on'}")
    messages = run(a.agent, check_grants=not a.broken)
    for m in messages:
        if m["role"] == "tool":
            label = f"{m['tool']} [{m['effect']}]" if m["effect"] else m["tool"]
            result = json.dumps(m["result"]) if isinstance(m["result"], dict) else m["result"]
            print(f"  tool       {label:<22} -> {result}")
        else:
            print(f"  {m['role']:<10} {m['content']}")
    ran = [m for m in messages if m["role"] == "tool" and m["effect"] and m["tool"] not in AGENTS[a.agent]["tools"]]
    if ran:
        print(textwrap.fill(f"The {a.agent} agent ran {', '.join(m['tool'] for m in ran)}, which it was never "
                            "granted. Whatever stopped it next was the tool's own check: one layer of two.", 72))


if __name__ == "__main__":
    main()
