"""Drive `claude -p` from a script: output formats, --json-schema, --max-turns, and how to read the result.

What you'll learn
  - The three `--output-format` values and how a script consumes each: `text` (just the answer),
    `json` (one result object with cost, turns, session id and `result`), and `stream-json`
    (one JSON event per line, ending with the `result` line; used together with `--verbose`).
  - `--json-schema` puts schema-shaped data in `structured_output`. The `result` field then holds
    the same JSON as a string, so read `structured_output`, and treat a success without it as a failure.
  - How to decide whether a run worked: no `result` event means the process died; then check
    `stop_reason` first (a refusal, "refusal", usually arrives as subtype "success"), then
    `terminal_reason` (an API failure can arrive as subtype "success" too), then `subtype`; any
    `error_*` subtype or `is_error: true` means the script should fail.
  - Why `--max-turns` and `--max-budget-usd` belong on every unattended run, and what a run that hits
    the turn cap looks like (`error_max_turns`, `terminal_reason: "max_turns"`, no `result` field).
  - That a `dontAsk` run with a tool it may not use finishes with "success" plus `permission_denials`:
    the run worked, but the task may be incomplete.

How to run (from labs/)
  python3 core-4/headless_runner.py                            # stream-json replay of a read-only exploration
  python3 core-4/headless_runner.py --format json              # the same run as one JSON object
  python3 core-4/headless_runner.py --format text
  python3 core-4/headless_runner.py --schema                   # --json-schema -> structured_output
  python3 core-4/headless_runner.py --scenario max-turns       # a run stopped by --max-turns
  python3 core-4/headless_runner.py --scenario denied          # dontAsk denies Bash
  python3 core-4/headless_runner.py --scenario all             # every scenario in one verdict table
  python3 core-4/headless_runner.py --scenario max-turns --ci  # exit with the verdict code, like a CI step
  python3 core-4/headless_runner.py --real --schema --model haiku --max-budget-usd 0.05
  Real runs (opt-in) cost money, run in a temp copy of common/samples/tiny-app, are read-only and capped.

What to observe
  - The printed command line: the prompt right after `-p`, `--output-format`, `--verbose` for
    stream-json, the caps, `--permission-mode dontAsk` and the read-only tool list.
  - In stream-json, one assistant event per content block: a text block and a tool call from one model
    response share `message.id`. Per-step `stop_reason` is null; the final answer is on the `result` line.
  - The verdict table: only `explore`, `error-recovery`, `denied` and `structured` pass; `max-turns`
    fails, and `denied` passes with a warning you should act on.

Exercises
  1. Run `--schema --scenario explore`. The run "succeeded" but has no `structured_output`: why does
     the verdict fail it, and what would a script that only read `result` have done?
  2. Write the jq one-liners from the "consume it" section into a shell script that exits non-zero on a
     failed run. Which field do you test first?
  3. With `--real`, rerun `--scenario max-turns --max-turns 1`. Compare `num_turns` with the cap: the
     docs say to read it from the result rather than recompute it.
  4. Add `--scenario denied --real` and look at the stderr warning about Bash: why is Bash in `--tools`
     but not in `--allowedTools`, and what does `dontAsk` do with it?

Docs: https://code.claude.com/docs/en/headless ; https://code.claude.com/docs/en/cli-reference ;
https://code.claude.com/docs/en/agent-sdk/typescript#sdkresultmessage ; https://code.claude.com/docs/en/agent-sdk/structured-outputs ;
https://code.claude.com/docs/en/agent-sdk/python#resulterror (stop_reason, then terminal_reason, then subtype; 2026-10-23)
"""
from __future__ import annotations

import argparse
import json
import shlex
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

sys.dont_write_bytecode = True  # keep __pycache__ out of the lab folders
HERE = Path(__file__).resolve().parent
LABS = HERE.parent
sys.path.insert(0, str(LABS))
sys.path.insert(0, str(LABS / "core-1"))
from common.cc import (AssistantEvent, HeadlessRun, ResultEvent, SystemEvent, UserEvent,  # noqa: E402
                       add_real_args, print_summary, run_from_args, summarize)
from common.pretty import c, header, kv, step, table  # noqa: E402

# The docs' example schema for --json-schema (headless, "Get structured output").
FUNCTIONS_SCHEMA: Dict[str, Any] = {"type": "object",
                                    "properties": {"functions": {"type": "array", "items": {"type": "string"}}},
                                    "required": ["functions"]}

# scenario -> (fixture under common/fixtures, prompt a real run uses, tools, needs the schema)
# Fixture formats: common/fixtures/FIXTURES.md. "denied" adds Bash to --tools (availability) but not to
# --allowedTools (pre-approval), so dontAsk denies Bash outside the read-only set, as in the recorded real run.
SCENARIOS: Dict[str, Tuple[str, str, Tuple[str, ...], bool]] = {
    "explore": ("explore_readonly", "List the modules in tinyapp/ with one line on what each does. Read only: do not change files.",
                ("Read", "Grep", "Glob"), False),
    "error-recovery": ("tool_error_recovery", "Read tinyapp/discounts.py and tell me where DISCOUNTS is defined.",
                       ("Read", "Grep", "Glob"), False),
    "max-turns": ("max_turns_stop", "Read tinyapp/discounts.py, then read every module and summarize each one.",
                  ("Read", "Grep", "Glob"), False),
    "denied": ("permission_denied", "Run the test suite with python3 -m unittest and report the result.",
               ("Read", "Grep", "Glob", "Bash"), False),
    "structured": ("structured_output", "List the public functions defined in tinyapp/pricing.py.",
                   ("Read", "Grep", "Glob"), True),
}
FORMATS = ("text", "json", "stream-json")  # --output-format values (cli-reference)
# The cap each fixture was recorded with, where it matters: max_turns_stop.jsonl is a --max-turns 2 run
# ("Reached maximum number of turns (2)", num_turns 3). Replays show that cap unless you pass your own.
RECORDED_MAX_TURNS = {"max-turns": 2}


# ----------------------------------------------------------------------------
# Verdict: what a CI step should do with a run
# ----------------------------------------------------------------------------
def verdict(res: Optional[ResultEvent], *, schema: bool, returncode: int = 0) -> Tuple[int, str, List[str]]:
    """(exit code a script should use, one-line reason, warnings) for one run.

    Order follows the docs: no result event -> the process didn't finish (killed, timed out; SIGTERM exits
    143, headless page); then stop_reason, terminal_reason, subtype (agent-sdk/python, ResultError): a
    refusal has stop_reason "refusal", usually with subtype "success", and an API failure can be subtype
    "success" with terminal_reason "api_error"; error_* subtypes and is_error fail; with --json-schema, a
    success without structured_output fails (structured-outputs page).
    """
    warnings: List[str] = []
    if res is None:
        return 1, f"no result event (process exit {returncode}): the run didn't finish", warnings
    tr = res.terminal_reason
    if res.stop_reason == "refusal":
        return 1, f"stop_reason='refusal': the model declined (terminal_reason {tr!r}, subtype {res.subtype!r})", warnings
    if tr not in (None, "completed"):
        return 1, f"terminal_reason={tr!r} (subtype {res.subtype!r})", warnings
    if res.subtype != "success" or res.is_error:
        errs = "; ".join(map(str, res.errors)) or "no errors[] given"
        return 1, f"subtype={res.subtype!r} is_error={res.is_error}: {errs}", warnings
    if res.api_error_status:
        return 1, f"api_error_status={res.api_error_status}", warnings
    if schema and res.structured_output is None:
        return 1, "success, but --json-schema was set and structured_output is missing", warnings
    if res.permission_denials:
        names = ", ".join(sorted({str(d.get("tool_name")) for d in res.permission_denials}))
        warnings.append(f"{len(res.permission_denials)} permission denial(s) ({names}): the task may be incomplete")
    return 0, "success" + (" with structured_output" if schema else ""), warnings


# ----------------------------------------------------------------------------
# Consuming each output format
# ----------------------------------------------------------------------------
def jq_hints(fmt: str, schema: bool) -> List[str]:
    """Shell one-liners for each format (headless page uses jq the same way)."""
    if fmt == "text":
        return ['answer=$(claude -p "..." --output-format text)    # stdout is just the final answer',
                'echo $?                                            # 0 on success, non-zero when the run fails']
    if fmt == "json":
        lines = ['claude -p "..." --output-format json > run.json',
                 "jq -r '.stop_reason, .terminal_reason, .subtype, .is_error' run.json   # check these, in this order, before using the answer",
                 "jq -r '.total_cost_usd, .num_turns, .session_id' run.json"]
        lines.append("jq '.structured_output' run.json" if schema else "jq -r '.result' run.json")
        return lines
    return ['claude -p "..." --output-format stream-json --verbose > run.jsonl',
            "jq -c 'select(.type==\"assistant\") | .message.content[] | select(.type==\"tool_use\") | {name, input}' run.jsonl",
            "tail -n 1 run.jsonl | jq '{stop_reason, terminal_reason, subtype, num_turns, total_cost_usd}'   # the last line is the result"]


def _clip(s: Any, n: int = 72) -> str:
    t = " ".join(str(s).split())
    return t if len(t) <= n else t[: n - 1] + "…"


def progress_lines(run: HeadlessRun) -> List[str]:
    """One line per stream-json event, the way a CI log might show progress."""
    out: List[str] = []
    for ev in run.events:
        if isinstance(ev, SystemEvent) and ev.subtype == "init":
            out.append(f"[init] model={ev.model} permissionMode={ev.permission_mode} tools={','.join(ev.tools)} "
                       f"v{ev.get('claude_code_version')}")
        elif isinstance(ev, SystemEvent) and ev.subtype == "permission_denied":
            out.append(f"[denied] {ev.get('tool_name')} ({ev.get('decision_reason_type')})")
        elif isinstance(ev, SystemEvent):
            out.append(f"[system/{ev.subtype}]")
        elif isinstance(ev, AssistantEvent):
            mid = (ev.message_id or "?")[-2:]
            for b in ev.content:
                if b.get("type") == "text" and b.get("text", "").strip():
                    out.append(f"[msg {mid}] text: {_clip(b['text'])}")
                elif b.get("type") == "tool_use":
                    out.append(f"[msg {mid}] tool_use {b.get('name')} {_clip(json.dumps(b.get('input', {}), sort_keys=True), 60)}")
        elif isinstance(ev, UserEvent):
            for r in ev.tool_results:
                body = r.get("content")
                body = body if isinstance(body, str) else json.dumps(body)
                status = c("ERROR", "red") if r.get("is_error") else "ok"
                out.append(f"[result] {status} {len(body)} chars: {_clip(body, 50)}")
        elif isinstance(ev, ResultEvent):
            out.append(f"[result/{ev.subtype}] stop_reason={ev.stop_reason} terminal_reason={ev.terminal_reason} "
                       f"turns={ev.num_turns} cost=${(ev.total_cost_usd or 0):.6f}")
        else:
            out.append(f"[{ev.kind}]")
    return out


def show_run(run: HeadlessRun, fmt: str, schema: bool) -> None:
    step(2, f"Consume it ({fmt})")
    for line in jq_hints(fmt, schema):
        print("  " + c(line, "gray"))
    print()
    if fmt == "text":
        print("  stdout: " + (run.text.strip() or c("(empty: an error result prints no answer text)", "gray")))
        if run.mode == "replay":
            print(c("  (replay: a text run prints only the result text, so the script sees no cost or turn data)", "gray"))
        return
    if fmt == "json":
        res = run.result
        if res is None:
            print("  (no JSON object on stdout)")
            return
        keys = ("type", "stop_reason", "terminal_reason", "subtype", "is_error", "num_turns", "duration_ms",
                "total_cost_usd", "session_id", "permission_denials", "errors", "result", "structured_output")
        for k in keys:
            if k in res.raw:
                kv(k, _clip(json.dumps(res.raw[k]), 90))
        return
    for line in progress_lines(run):
        print("  " + line)


# ----------------------------------------------------------------------------
# Main
# ----------------------------------------------------------------------------
def run_scenario(args: argparse.Namespace, name: str, fmt: str, schema: bool) -> HeadlessRun:
    fixture, prompt, tools, needs_schema = SCENARIOS[name]
    if args.prompt:
        prompt = args.prompt
    use_schema = schema or needs_schema
    kwargs: Dict[str, Any] = dict(tools=tools, output_format=fmt, allow_writes="Bash" in tools,
                                  allowed_tools=[t for t in tools if t != "Bash"])
    if use_schema:
        kwargs["json_schema"] = FUNCTIONS_SCHEMA
    recorded = RECORDED_MAX_TURNS.get(name)
    if recorded and not args.real and not _flag_given("--max-turns"):
        args = argparse.Namespace(**{**vars(args), "max_turns": recorded})
    return run_from_args(args, prompt, fixture=fixture, **kwargs)


def _flag_given(flag: str) -> bool:
    return any(a == flag or a.startswith(flag + "=") for a in sys.argv[1:])


def verdict_table(args: argparse.Namespace) -> int:
    header("All scenarios (replayed as --output-format json)")
    rows = []
    for name, (fixture, _, _, needs_schema) in SCENARIOS.items():
        run = run_scenario(args, name, "json", needs_schema)
        res = run.result
        code, why, warns = verdict(res, schema=needs_schema, returncode=run.returncode)
        mark = c("PASS", "green") if code == 0 and not warns else (c("WARN", "yellow") if code == 0 else c("FAIL", "red"))
        rows.append([name, fixture, res.stop_reason if res else "-", res.terminal_reason if res else "-",
                     res.subtype if res else "-",
                     res.num_turns if res else "-", len(res.permission_denials) if res else "-", mark,
                     _clip(why + ("; " + warns[0] if warns else ""), 60)])
    table(rows, ["scenario", "fixture", "stop_reason", "terminal_reason", "subtype", "turns", "denials", "verdict", "why"])
    print(c("\nRead stop_reason, then terminal_reason, then subtype, and structured_output (not result) when you pass "
            "--json-schema.", "gray"))
    return 0


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0],
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--format", choices=FORMATS, default=None, help="--output-format (default stream-json; json with --schema)")
    ap.add_argument("--schema", action="store_true", help="pass the docs' --json-schema example (implies --format json)")
    ap.add_argument("--scenario", choices=list(SCENARIOS) + ["all"], default=None,
                    help="which recorded run to replay (default: explore, or structured with --schema)")
    ap.add_argument("--prompt", default=None, help="prompt for a --real run (default: the scenario's prompt)")
    ap.add_argument("--ci", action="store_true", help="exit with the verdict code (0 pass, 1 fail), as a CI step would")
    add_real_args(ap, max_turns=3, max_budget_usd=0.10)
    args = ap.parse_args()
    if args.prompt is not None and (not args.prompt.strip() or args.prompt.lstrip().startswith("-")):
        ap.error("--prompt must be non-empty and must not start with '-' (the CLI would read it as a flag)")
    if args.repo and not args.real:
        ap.error("--repo only applies to --real runs")
    if args.scenario == "all":
        if args.real:
            ap.error("--scenario all replays every fixture; pick one scenario for --real")
        return verdict_table(args)
    scenario = args.scenario or ("structured" if args.schema else "explore")
    schema = args.schema or SCENARIOS[scenario][3]
    fmt = args.format or ("json" if schema else "stream-json")
    if schema and fmt != "json":
        # The headless page documents --json-schema together with --output-format json.
        ap.error(f"--json-schema is read from the json result object; use --format json, not {fmt}")

    run = run_scenario(args, scenario, fmt, schema)  # validates the caps first (exit 2 on unsafe values)
    header(f"claude -p, headless · scenario {scenario} · {fmt}" + (" · --json-schema" if schema else ""))
    step(1, "The command" + (" (replay: this is what --real would run)" if run.mode == "replay" else ""))
    print("  " + shlex.join(run.argv))
    for w in run.warnings:
        print(c(f"  warning: {w}", "yellow"))
    if scenario == "denied":
        print(c("  Bash is in --tools (it exists) but not in --allowedTools (not pre-approved): dontAsk denies Bash outside "
                "the read-only set.", "gray"))
    recorded = RECORDED_MAX_TURNS.get(scenario)
    if recorded and run.mode == "replay" and _flag_given("--max-turns") and args.max_turns != recorded:
        print(c(f"  note: the recorded run used --max-turns {recorded}; a replay shows that run whatever cap you pass.", "yellow"))
    print()
    show_run(run, fmt, schema)

    res = run.result
    print()
    step(3, "Verdict")
    if fmt == "text":
        # A text consumer sees only stdout and the exit status (headless: 0 on success, non-zero on failure).
        code, why, warns = (0 if run.returncode == 0 else 1), f"process exit status {run.returncode}", []
        if res is None and run.mode == "replay":
            res = None
    else:
        code, why, warns = verdict(res, schema=schema, returncode=run.returncode)
    kv("a CI step would exit", f"{code}  ({why})")
    for w in warns:
        print(c(f"  warning: {w}", "yellow"))
    if res is not None and fmt != "text":
        print()
        step(4, "Summary from the result event (read num_turns and cost here, don't recompute them)")
        print_summary(summarize(run.events))
        if fmt == "json":
            print(c("  (json output carries only the result object: tool-call counts need stream-json)", "gray"))
    if run.mode == "real":
        print(c("\n[real] Even with --no-session-persistence the CLI may leave an empty "
                "~/.claude/projects/<tmp-dir>/memory/ folder for the temp copy; delete it if you like.", "gray"))
        if run.returncode not in (0, 1) and run.stderr:
            print(c(f"[real] stderr: {_clip(run.stderr, 200)}", "yellow"))
    return code if args.ci else 0


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