#!/usr/bin/env python3
"""Agents 2 · sdk_agent: query() plus a custom tool served by an in-process MCP server.

The Agent SDK runs the same loop as `claude -p`, but you own the process: you pick the tools, and you can
add your own as Python functions. `@tool` turns an async function into a tool definition,
`create_sdk_mcp_server` wraps tools in an MCP server that runs inside your process (no subprocess), and
Claude sees each one as `mcp__<server>__<tool>`. This lab gives Claude one tool, `quote_cart`, that prices
a cart with the tiny-app sample's own pricing code, and removes every built-in tool so it can't do
anything else.

What you'll learn:
    * The four parts of a custom tool: name, description, input schema (a type map or JSON Schema), and an
      async handler that returns {"content": [...], "is_error"?: bool}.
    * Availability vs permission: `tools=[]` removes every built-in; `allowed_tools` only pre-approves.
      With permission_mode="dontAsk", a call nothing approves is denied instead of prompting.
    * Errors: return is_error with a message Claude can act on; an uncaught exception also becomes an
      error result, and the loop keeps going either way.
    * Annotations are hints, not enforcement: readOnlyHint lets read-only tools run in parallel.
    * Reading the stream: SystemMessage init, one AssistantMessage per content block, UserMessage tool
      results, and a final ResultMessage with cost and turns. Iterate to the end; don't `break`.

How to run (from labs/):
    python3 agents-2/sdk_agent.py                 # call the handler directly, then replay a recorded run (offline fake)
    python3 agents-2/sdk_agent.py --real --model haiku --max-budget-usd 0.05
        # costs money: Python 3.10+ with `pip install claude-agent-sdk`; runs in a temp copy of tiny-app
    python3 agents-2/sdk_agent.py --real --save   # also write the messages to agents-2/out/sdk_agent_real.json

What to observe:
    * Direct handler calls: a good cart, a zero quantity (is_error true, with a fix-it message), and an
      unknown discount code (not an error: the pricing rules give 0% off).
    * The replay: the init message lists the in-process server as connected and only the MCP tools;
      Claude calls mcp__tinyapp__quote_cart once; the result matches the direct call.
    * Python's @tool forwards only `content` and `is_error`; there is no structuredContent.

Exercises:
    1. Add a `list_discount_codes` tool with annotations=ToolAnnotations(readOnlyHint=True) and ask a
       question that needs both tools. Do the calls share one message_id (parallel)?
    2. Remove `allowed_tools` and run --real. What does dontAsk do with the call, and where does the denial
       show up (ResultMessage.permission_denials)?
    3. Raise an exception inside the handler instead of returning is_error. What text does Claude get?
    4. Add `tools=["Read"]` and ask "what's the CA tax rate?". Does Claude read pricing.py or call your tool?

Docs (fetched 2026-10-20):
    https://code.claude.com/docs/en/agent-sdk/custom-tools   (@tool, create_sdk_mcp_server, mcp__ naming, errors, annotations, tools vs allowed_tools)
    https://code.claude.com/docs/en/agent-sdk/python         (query(), message and block types, ResultMessage fields;
                                                              ResultError: stop_reason, then terminal_reason, then subtype)
    https://code.claude.com/docs/en/agent-sdk/agent-loop     (one AssistantMessage per content block; iterate to completion)
    https://code.claude.com/docs/en/agent-sdk/permissions    (allowedTools + dontAsk for a locked-down agent)
"""
from __future__ import annotations

import sys

sys.dont_write_bytecode = True  # before any other import: keep labs/ free of __pycache__

import argparse
import asyncio
import importlib
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))

import _sdk_common as lab  # noqa: E402
from common.pretty import c, header, kv, step  # noqa: E402

SAMPLE = lab.LABS / "common" / "samples" / "tiny-app"
SERVER_NAME = "tinyapp"
TOOL = f"mcp__{SERVER_NAME}__quote_cart"
FIXTURE = lab.FIXTURES / "custom_tool.jsonl"
PROMPT = ("Quote this cart with the quote_cart tool: region CA, discount code WELCOME10, 3 apples at 120 cents "
          "and 1 pear at 250 cents. Reply with the total in dollars and one line on how it was computed.")

QUOTE_SCHEMA = {
    "type": "object",
    "properties": {
        "region": {"type": "string", "description": "Two-letter tax region, e.g. CA (unknown regions are untaxed)"},
        "code": {"type": "string", "description": "Discount code, e.g. WELCOME10 (optional; case-sensitive)"},
        "items": {"type": "array", "minItems": 1, "items": {
            "type": "object",
            "properties": {"sku": {"type": "string"}, "unit_cents": {"type": "integer", "minimum": 0},
                           "qty": {"type": "integer", "minimum": 1}},
            "required": ["sku", "unit_cents"]}},
    },
    "required": ["items"],
}


def _tinyapp() -> Any:
    """Import tiny-app's own pricing code from the sample (read-only; no bytecode is written)."""
    if str(SAMPLE) not in sys.path:
        sys.path.insert(0, str(SAMPLE))
    return importlib.import_module("tinyapp")


def make_tools(sdk: Any) -> List[Any]:
    """Define the custom tool against whichever SDK module is active (real or fake)."""

    @sdk.tool("quote_cart", "Price a shopping cart with tiny-app's rules: subtotal, discount, tax after the discount, "
                            "total. All amounts are integer cents.", QUOTE_SCHEMA,
              annotations=sdk.ToolAnnotations(readOnlyHint=True, destructiveHint=False, openWorldHint=False))
    async def quote_cart(args: Dict[str, Any]) -> Dict[str, Any]:
        ta = _tinyapp()
        region = str(args.get("region") or "OR")
        code = args.get("code") or None
        items = args.get("items") or []
        if not isinstance(items, list) or not items:
            return {"content": [{"type": "text", "text": "items must be a non-empty list of {sku, unit_cents, qty}"}], "is_error": True}
        cart = ta.Cart(region=region, discount_code=code)
        try:
            for it in items:
                cart.add(str(it["sku"]), int(it["unit_cents"]), int(it.get("qty", 1)))
        except (KeyError, TypeError, ValueError) as e:
            return {"content": [{"type": "text", "text": f"bad item {it!r}: {e}. Each item needs sku, unit_cents >= 0 "
                                                         "and qty >= 1."}], "is_error": True}
        m = ta.money
        lines = [f"subtotal {m(cart.subtotal())}",
                 f"discount -{m(cart.discount())} ({code or 'no code'})",
                 f"tax {m(cart.tax())} ({region.upper()}, on the discounted subtotal)",
                 f"total {m(cart.total())}"]
        return {"content": [{"type": "text", "text": "; ".join(lines)}]}

    return [quote_cart]


async def direct_calls(tools: List[Any]) -> None:
    """Handlers are plain async functions: test them without a model."""
    quote = tools[0]
    cases = [
        ("good cart", {"region": "CA", "code": "WELCOME10", "items": [{"sku": "apple", "unit_cents": 120, "qty": 3},
                                                                      {"sku": "pear", "unit_cents": 250}]}),
        ("zero quantity", {"region": "CA", "items": [{"sku": "apple", "unit_cents": 120, "qty": 0}]}),
        ("unknown code", {"region": "NY", "code": "welcome10", "items": [{"sku": "pear", "unit_cents": 250, "qty": 2}]}),
    ]
    for label, args in cases:
        out = await quote.handler(args)
        err = c(" is_error", "red") if out.get("is_error") else ""
        kv(label, out["content"][0]["text"] + err)


def options_for(sdk: Any, args: argparse.Namespace, server: Any, cwd: Optional[Path]) -> Any:
    kw: Dict[str, Any] = dict(
        mcp_servers={SERVER_NAME: server},
        tools=[],                 # availability: no built-in tools at all, only the MCP tool
        allowed_tools=[TOOL],     # approval: exactly this tool runs without asking
        permission_mode="dontAsk",  # anything else that would prompt is denied
    )
    if args.real:
        kw.update(lab.base_options(args, cwd))  # cwd, caps, setting_sources=[], strict_mcp_config, env
    else:
        kw.update(max_turns=args.max_turns, max_budget_usd=args.max_budget_usd)
    return sdk.ClaudeAgentOptions(**kw)


async def amain(args: argparse.Namespace) -> int:
    sdk = lab.load_sdk(args.real)
    header(f"Agents 2 · sdk_agent: query() + an in-process MCP tool ({'real SDK' if args.real else 'offline fake'})")
    tools = make_tools(sdk)
    server = sdk.create_sdk_mcp_server(name=SERVER_NAME, version="1.0.0", tools=tools)

    step(1, f"Call the {tools[0].name} handler directly (no model)")
    await direct_calls(tools)

    step(2, "The options: what exists, what is approved, and the caps")
    kv("mcp_servers", f"{{'{SERVER_NAME}': create_sdk_mcp_server(...)}}  -> tool name {TOOL}")
    kv("tools", "[]  (no built-ins)")
    kv("allowed_tools", f"[{TOOL!r}]")
    kv("permission_mode", "dontAsk")
    kv("caps", f"max_turns={args.max_turns}, max_budget_usd={args.max_budget_usd}")

    cwd = None
    if args.real:
        warnings = lab.check_real(args, tools=[], allowed_tools=[TOOL], permission_mode="dontAsk",
                                     mcp_tools={SERVER_NAME: [t.name for t in tools]})
        cwd = lab.run_dir(args)
        lab.cost_notice(args, cwd, warnings)
    options = options_for(sdk, args, server, cwd)

    step(3, "Run query() and read every message" + ("" if args.real else f" (replaying {FIXTURE.relative_to(lab.LABS)})"))
    msgs, err = await lab.collect(sdk, PROMPT, options, fixture=FIXTURE)
    res = lab.result_of(sdk, msgs)
    calls = [b for m in msgs if isinstance(m, sdk.AssistantMessage) for b in m.content if isinstance(b, sdk.ToolUseBlock)]
    print()
    kv("tool calls", ", ".join(b.name for b in calls) or "none")
    if err is not None:
        kv("query() raised", f"{type(err).__name__}: {str(err).splitlines()[0]}")
    if args.real and args.save:
        kv("saved", str(lab.save_messages("sdk_agent", msgs)))
    if res is None:
        print(c("no ResultMessage: the run didn't finish", "red"))
        return 1
    if args.real:
        lab.explain_failure(res, args)
    # stop_reason, then terminal_reason, then subtype (agent-sdk/python): a refusal usually says "success", and
    # so do api_error, prompt_too_long and budget_exhausted.
    ok = (res.stop_reason != "refusal" and res.terminal_reason in (None, "completed") and res.subtype == "success"
          and not res.is_error and any(b.name == TOOL for b in calls))
    print(c("\nThe model never saw a built-in tool: everything it did went through quote_cart.", "gray") if ok else
          c("\nThe run ended without a successful quote_cart call; read the messages above.", "yellow"))
    return 0 if ok else 1


def main(argv: Optional[Sequence[str]] = None) -> int:
    ap = argparse.ArgumentParser(description="Agent SDK query() with a custom in-process MCP tool.",
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    lab.add_sdk_args(ap, max_turns=3, max_budget_usd=0.05)
    args = ap.parse_args(argv)
    return asyncio.run(amain(args))


if __name__ == "__main__":
    raise SystemExit(main())
