#!/usr/bin/env python3
"""Agents 2 · sdk_structured: structured output with a JSON Schema, and every way it can fail.

Pass `output_format={"type": "json_schema", "schema": {...}}` and the final ResultMessage carries
`structured_output`, validated by the SDK against the schema (JSON Schema draft-07). The CLI equivalent is
`claude -p --output-format json --json-schema '<schema>'`. A pipeline that consumes the output must also
handle the two documented failures: `error_max_structured_output_retries`, and a `success` result with no
`structured_output` at all.

What you'll learn:
    * The option shape, and why you read `structured_output` rather than parsing `result` (in a real run,
      `result` held the same JSON as a string and `stop_reason` was "tool_use").
    * The acceptance rule from the docs: `stop_reason` first (a refusal, "refusal", usually says subtype
      "success"), then `terminal_reason` (when present) must be "completed", then `subtype == "success"`,
      AND structured_output is present. Treat the rest as failures, and check `errors` to tell a
      validation failure from a model-fallback retraction.
    * That a single-shot query() raises after yielding an error result: catch it, but keep the
      ResultMessage you already received.
    * Validating again on your side is cheap insurance (the stdlib checker here covers the draft-07
      keywords this schema uses).

How to run (from labs/):
    python3 agents-2/sdk_structured.py             # replay success + both failure shapes (offline fake)
    python3 agents-2/sdk_structured.py --schema    # print the schema and the matching CLI command
    python3 agents-2/sdk_structured.py --real --model haiku --max-budget-usd 0.05
        # costs money: Python 3.10+ and claude-agent-sdk; read-only tools in a temp copy of tiny-app

What to observe:
    * Replay 1: structured_output {"functions": [...]} passes the schema, while `result` is the same JSON
      as a string.
    * Replay 2: success with no structured_output is reported as a FAILURE.
    * Replay 3: error_max_structured_output_retries arrives, and then query() raises ResultError.

Exercises:
    1. Tighten the schema with "minItems": 3 and "uniqueItems": true and extend `validate()` to check them.
    2. Add a field the model can't know (e.g. "author") as required. Run --real and see which failure you get.
    3. Generate the schema from a Pydantic model (`Model.model_json_schema()`) in a 3.10+ venv and compare.

Docs (fetched 2026-10-20):
    https://code.claude.com/docs/en/agent-sdk/structured-outputs   (output_format, draft-07, error handling)
    https://code.claude.com/docs/en/headless#get-structured-output (--output-format json --json-schema)
    https://code.claude.com/docs/en/agent-sdk/python#resultmessage (structured_output, errors, subtypes)
    https://code.claude.com/docs/en/agent-sdk/python#resulterror   (stop_reason, then terminal_reason, then subtype)
"""
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 json
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple

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

SCHEMA: Dict[str, Any] = {
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {"functions": {"type": "array", "items": {"type": "string"},
                                 "description": "names of the top-level functions defined in tinyapp/pricing.py"}},
    "required": ["functions"],
    "additionalProperties": False,
}
PROMPT = "List the names of the top-level functions defined in tinyapp/pricing.py."
REPLAYS: List[Tuple[str, Any]] = [
    ("success with structured_output", "structured_output"),  # common/fixtures/json/structured_output.json
    ("success WITHOUT structured_output", lab.FIXTURES / "structured_missing.json"),
    ("error_max_structured_output_retries", lab.FIXTURES / "structured_retries_exhausted.json"),
]


def validate(value: Any, schema: Dict[str, Any], path: str = "$") -> List[str]:
    """Check `value` against the draft-07 keywords used here: type, properties, required, items,
    additionalProperties, enum. Returns a list of problems (empty = valid)."""
    problems: List[str] = []
    t = schema.get("type")
    types = {"object": dict, "array": list, "string": str, "integer": int, "number": (int, float), "boolean": bool, "null": type(None)}
    if t and not isinstance(value, types[t]) or (t in ("integer", "number") and isinstance(value, bool)):
        return [f"{path}: expected {t}, got {type(value).__name__}"]
    if "enum" in schema and value not in schema["enum"]:
        problems.append(f"{path}: {value!r} not in {schema['enum']}")
    if t == "object":
        props = schema.get("properties", {})
        problems += [f"{path}: missing required {k!r}" for k in schema.get("required", []) if k not in value]
        if schema.get("additionalProperties") is False:
            problems += [f"{path}: unexpected property {k!r}" for k in value if k not in props]
        for k, sub in props.items():
            if k in value:
                problems += validate(value[k], sub, f"{path}.{k}")
    if t == "array" and isinstance(schema.get("items"), dict):
        for i, item in enumerate(value):
            problems += validate(item, schema["items"], f"{path}[{i}]")
    return problems


def accept(sdk: Any, res: Any) -> Tuple[bool, str]:
    """The documented acceptance rule, plus a local re-validation."""
    if res is None:
        return False, "no ResultMessage (the process failed before finishing)"
    tr = res.terminal_reason
    if res.stop_reason == "refusal":  # stop_reason first (agent-sdk/python): a refusal usually says subtype "success"
        return False, f"the model declined: stop_reason=refusal (terminal_reason={tr}, subtype={res.subtype})"
    if res.subtype == "error_max_structured_output_retries" or tr == "structured_output_retry_exhausted":
        return False, f"no valid output after retries; errors={res.errors}"
    if tr not in (None, "completed"):  # then terminal_reason, before subtype: "success" can carry api_error and others
        return False, f"run stopped before completing: terminal_reason={tr} (subtype={res.subtype})"
    if res.subtype != "success" or res.is_error:
        return False, f"run failed: terminal_reason={res.terminal_reason} subtype={res.subtype}"
    if res.structured_output is None:
        return False, "success but no structured_output: the docs say to treat this as a failure"
    problems = validate(res.structured_output, SCHEMA)
    if problems:
        return False, "structured_output fails the schema: " + "; ".join(problems)
    return True, f"structured_output = {json.dumps(res.structured_output)}"


async def amain(args: argparse.Namespace) -> int:
    if args.schema:
        print(json.dumps(SCHEMA, indent=2))
        print("\nCLI: claude -p \"" + PROMPT + "\" --output-format json --json-schema '" + json.dumps(SCHEMA, separators=(",", ":"))
              + "' --tools Read,Grep,Glob --allowedTools Read,Grep,Glob --permission-mode dontAsk --max-turns 4 --max-budget-usd 0.05")
        return 0
    sdk = lab.load_sdk(args.real)
    header(f"Agents 2 · sdk_structured: output_format json_schema ({'real SDK' if args.real else 'offline fake'})")
    if args.real:
        tools = ["Read", "Grep", "Glob"]
        warnings = lab.check_real(args, tools=tools, allowed_tools=tools, permission_mode="dontAsk")
        cwd = lab.run_dir(args)
        lab.cost_notice(args, cwd, warnings)
        options = sdk.ClaudeAgentOptions(tools=tools, allowed_tools=tools, permission_mode="dontAsk",
                                         output_format={"type": "json_schema", "schema": SCHEMA}, **lab.base_options(args, cwd))
        msgs, err = await lab.collect(sdk, PROMPT, options)
        res = lab.result_of(sdk, msgs)
        if err is not None:
            kv("query() raised", f"{type(err).__name__}: {str(err).splitlines()[0]}")
        ok, why = accept(sdk, res)
        kv("verdict", c("ACCEPT", "green") if ok else c("REJECT", "red"))
        kv("why", why)
        if args.save:
            kv("saved", str(lab.save_messages("sdk_structured", msgs)))
        lab.explain_failure(res, args)
        return 0 if ok else 1

    options = sdk.ClaudeAgentOptions(tools=["Read", "Grep", "Glob"], allowed_tools=["Read", "Grep", "Glob"],
                                     permission_mode="dontAsk", output_format={"type": "json_schema", "schema": SCHEMA},
                                     max_turns=args.max_turns, max_budget_usd=args.max_budget_usd)
    expected = [True, False, False]
    surprises = 0
    for n, ((label, fixture), want) in enumerate(zip(REPLAYS, expected), 1):
        step(n, f"replay: {label}")
        msgs, err = await lab.collect(sdk, PROMPT, options, fixture=fixture, show=False)
        res = lab.result_of(sdk, msgs)
        if res is not None:
            kv("ResultMessage", f"stop_reason={res.stop_reason} terminal_reason={res.terminal_reason} "
                                f"subtype={res.subtype} is_error={res.is_error}")
            kv("result (string)", repr(res.result)[:80] if res.result is not None else "None (result exists only on success)")
        if err is not None:
            kv("query() raised", f"{type(err).__name__} after yielding the result (subtype={getattr(err, 'subtype', None)})")
        ok, why = accept(sdk, res)
        kv("verdict", (c("ACCEPT", "green") if ok else c("REJECT", "red")) + f"  {why}")
        surprises += ok != want
    print(c("\nOnly the first replay is usable. A pipeline that checked subtype alone would accept the second.", "gray"))
    return 1 if surprises else 0


def main(argv: Optional[Sequence[str]] = None) -> int:
    ap = argparse.ArgumentParser(description="Agent SDK structured output with a JSON Schema.")
    ap.add_argument("--schema", action="store_true", help="print the schema and the CLI equivalent, then exit")
    lab.add_sdk_args(ap, max_turns=4, max_budget_usd=0.05)
    args = ap.parse_args(argv)
    return asyncio.run(amain(args))


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