#!/usr/bin/env bash
# Real demos for P039 "Claude API vs Claude Pro: Why Your Subscription Doesn't Include It".
# A made-up coffee shop (Kettle & Bean): Ana wants a script that summarizes support emails.
#   summarize.py  her script: the official Anthropic Python SDK, which needs an API key
#   on-plan       the same request through Claude Code (headless), signed in with this Mac's Claude plan
#   price         what a request costs at the API's published list prices, from its token counts
# Only a FAKE key is ever used (sk-ant-api03- then FAKE0, short enough that our pre-commit secret guard lets it
# through): the real API answers it with 401.
# DEMO_STEPS=export,fakekey re-runs just those steps and merges them into the existing demo_output.json.
# ANTHROPIC_API_KEY and ANTHROPIC_AUTH_TOKEN are removed from the shell, so no real key is read or shown.
# Runs on the Mac (it needs the Claude Code login), from ~/api-lab outside this repo (so Claude Code can't read
# our AGENTS.md); commands are typed into one real interactive bash; commands + output go to demo_output.json.
set -euo pipefail
cd "$(dirname "$0")"
LAB="$HOME/api-lab"
rm -rf "$LAB"; mkdir -p "$LAB"
cp -R lab/. "$LAB/"
trap 'rm -rf "$LAB"' EXIT

python3 - "$LAB" <<'PY'
import fcntl, json, os, pty, re, select, struct, sys, termios, time, subprocess
LAB = sys.argv[1]
READY = re.compile(rb"__READY__:(.*?):__ ")
steps = {}
FAKE_KEY = "sk-ant-api03-" + "FAKE0"
ONLY = [x for x in os.environ.get("DEMO_STEPS", "").split(",") if x]

def clean(text):
    text = re.sub(r"\x1b\[[0-9;?]*[A-Za-z]|\x1b[()][A-Z0-9]", "", text)
    lines = [l.rstrip("\r").split("\r")[-1] for l in text.split("\n")]
    return "\n".join(l.rstrip() for l in lines).strip("\n")

class Shell:
    def __init__(self):
        pid, fd = pty.fork()
        if pid == 0:
            fcntl.ioctl(0, termios.TIOCSWINSZ, struct.pack("HHHH", 40, 80, 0, 0))
            os.chdir(LAB)
            env = {k: v for k, v in os.environ.items() if k not in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN")}
            os.execvpe("bash", ["bash", "--norc", "--noprofile", "-i"], dict(env, TERM="dumb"))
        self.fd, self.where = fd, ""
        os.write(fd, b"stty -echo; PS1='__REA''DY__:\\W:__ '\n")
        self.read()

    def read(self, timeout=600):
        buf, end = b"", time.time() + timeout
        while time.time() < end:
            if select.select([self.fd], [], [], 0.3)[0]:
                buf += os.read(self.fd, 65536)
                m = None
                for m in READY.finditer(buf):
                    pass
                if m:
                    self.where = m.group(1).decode()
                    return clean(buf[:m.start()].decode("utf-8", "replace"))
        raise SystemExit(f"timed out; last output: {buf[-400:]!r}")

    def run(self, key, cmd):
        shown = f"{self.where}$ {cmd}"
        os.write(self.fd, cmd.encode() + b"\n")
        t = time.time()
        out = self.read()
        steps[key] = {"cmd": shown, "out": out}
        print(f"--- {key} ({time.time()-t:.0f}s)\n{shown}\n{out}\n", flush=True)
        return out

s = Shell()
if ONLY:
    cmds = {"export": "export ANTHROPIC_API_KEY=" + FAKE_KEY, "fakekey": "python3 summarize.py emails/torn-bag.txt"}
    for k in ONLY:
        s.run(k, cmds[k])
    old = json.load(open("demo_output.json"))
    old.update(steps)
    json.dump(old, open("demo_output.json", "w"), indent=1, ensure_ascii=False)
    print("merged", ONLY, "into demo_output.json")
    sys.exit(0)
s.run("email", "cat emails/torn-bag.txt")
s.run("script", "cat summarize.py")
s.run("nokey", "python3 summarize.py emails/torn-bag.txt")
s.run("export", "export ANTHROPIC_API_KEY=" + FAKE_KEY)
s.run("fakekey", "python3 summarize.py emails/torn-bag.txt")
s.run("unset", "unset ANTHROPIC_API_KEY")
s.run("onplan", "./on-plan emails/torn-bag.txt")
tok = json.load(open(os.path.join(LAB, ".log", "on-plan.json")))
assert tok["model"].startswith("claude-sonnet-5-5"), tok
s.run("price", f"./price sonnet-5.5 {tok['in']} {tok['out']}")
s.run("month", f"./price --month 6000 {tok['in']} {tok['out']}")
claude_version = subprocess.run(["claude", "--version"], capture_output=True, text=True).stdout.strip()
import anthropic
steps["_meta"] = {"cmd": "", "out": json.dumps({"claude_code": claude_version, "model": tok["model"],
                   "sdk": anthropic.__version__, "tokens_in": tok["in"], "tokens_out": tok["out"],
                   "run_at": time.strftime("%Y-%m-%d %H:%M %Z")})}
json.dump(steps, open("demo_output.json", "w"), indent=1, ensure_ascii=False)
print("saved demo_output.json")
PY
