#!/usr/bin/env bash
# Real demos for P190 "How to Fix LLM API Rate Limit Errors (429)". Runs on the Mac (Docker Desktop): the API keys
# live only on the Mac, never on a render box.
# One container, ce-p190-laptop: a stock Ubuntu 24.04 with curl, jq, Python, requests and the OpenAI SDK
# (lab/Dockerfile), your scripts in ~/app. Every command shown is typed into a real interactive bash in a pty
# (demo_driver.py). Three APIs answer them:
#   the practice API  lab/app/practice_api.py on the laptop itself (a token bucket: 5 requests, then 1 a second);
#                     started off camera, and said to be a practice API on screen
#   Gemini            the free-tier key of the "Default Gemini Project" (no billing), through Google's
#                     OpenAI-compatible endpoint: every Gemini 429 in the video is real
#   OpenRouter        the free-tier key with a $0 limit (owner rule 2026-11-07: free models only); the demo uses up
#                     the day's free requests (they come back at 00:00 UTC), so its daily 429 is real
# The driver refuses to save any output that contains either key.
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p190
TOP="$(git rev-parse --show-toplevel)"
KEYS="$TOP/.gemini_keys.json"; [ -f "$KEYS" ] || KEYS="$HOME/cloudexplainers/.gemini_keys.json"
ORKEY="$TOP/.openrouter_api_key"; [ -f "$ORKEY" ] || ORKEY="$HOME/cloudexplainers/.openrouter_api_key"
cleanup() { docker rm -f $P-laptop >/dev/null 2>&1 || true; }
cleanup
[ -n "${KEEP:-}" ] || trap cleanup EXIT
docker build -q -t $P-laptop lab >/dev/null
GEMINI_API_KEY=$(python3 -c "import json,sys; print([k for k in json.load(open(sys.argv[1]))['projects']['gen-lang-client-0388842080']['keys'] if k['display_name'] == 'Default Gemini API Key'][0]['key_string'])" "$KEYS")
OPENROUTER_API_KEY=$(cat "$ORKEY")
export GEMINI_API_KEY OPENROUTER_API_KEY
docker run -d --name $P-laptop --hostname laptop -e GEMINI_API_KEY -e OPENROUTER_API_KEY $P-laptop sleep infinity >/dev/null
python3 demo_driver.py
