#!/usr/bin/env bash
# capital-region-meeting-asr: joiner bootstrap for an Apple Silicon Mac (macOS arm64).
# Public script. Contains no secrets. Safe to re-run.
#   curl -fsSL https://capital-region-meeting-asr.canalandcountry.workers.dev/join/bootstrap.sh | bash
# Optional env: CAPREG_HOST_LABEL (default m1-mbp), CAPREG_SKIP_SELFTEST=1
# Optional args (curl ... | bash -s -- --with-ocr --host-label m1-mbp):
#   --with-ocr        also install the meeting-docs OCR lane (sha256-verified ocr_agent.py + launchd LaunchAgent).
#   --host-label X    same as CAPREG_HOST_LABEL.
# From agent.py 1.2.0 on, re-joining is not needed for updates: the agent self-updates (sha256-verified) and
# starts/scales the OCR lane from GET /hosts/<host_label>/config. Lane counts change on the server, not here.
set -euo pipefail
WITH_OCR=0
while [ $# -gt 0 ]; do
  case "$1" in
    --with-ocr) WITH_OCR=1 ;;
    --host-label) shift; CAPREG_HOST_LABEL="${1:-}" ;;
    --host-label=*) CAPREG_HOST_LABEL="${1#*=}" ;;
    *) echo "unknown argument: $1" >&2; exit 2 ;;
  esac
  shift
done

BASE="${CAPREG_BASE:-https://capital-region-meeting-asr.canalandcountry.workers.dev}"
HOST_LABEL="${CAPREG_HOST_LABEL:-m1-mbp}"
ROOT="$HOME/capital-region-asr"
DIR="$ROOT/joiner"
TOKEN_FILE="$HOME/.secrets/capreg-telemetry-token"

say() { printf '\n==> %s\n' "$*"; }
die() { printf '\nERROR: %s\n' "$*" >&2; exit 1; }

say "capital-region-meeting-asr joiner bootstrap (host_label=$HOST_LABEL)"
[ "$(uname -s)" = "Darwin" ] || die "macOS only."
[ "$(uname -m)" = "arm64" ] || die "Apple Silicon (arm64) only: mlx-whisper needs an M-series GPU."

say "Checking Homebrew"
if ! command -v brew >/dev/null 2>&1; then
  if [ -x /opt/homebrew/bin/brew ]; then
    eval "$(/opt/homebrew/bin/brew shellenv)"
  else
    die "Homebrew not found. Install it from https://brew.sh (one command), open a new terminal, then re-run this script."
  fi
fi

say "Installing ffmpeg, yt-dlp, python@3.11 if missing"
for pkg in ffmpeg yt-dlp python@3.11; do
  if brew list --versions "$pkg" >/dev/null 2>&1; then
    echo "  $pkg: installed"
  else
    brew install "$pkg"
  fi
done
brew upgrade yt-dlp >/dev/null 2>&1 || true
PY="$(brew --prefix python@3.11)/bin/python3.11"
[ -x "$PY" ] || die "python3.11 not found at $PY"

say "Creating $DIR with a Python venv and mlx-whisper"
mkdir -p "$DIR"
if [ ! -x "$DIR/venv/bin/python" ]; then
  "$PY" -m venv "$DIR/venv"
fi
"$DIR/venv/bin/python" -m pip install --quiet --upgrade pip
"$DIR/venv/bin/python" -m pip install --quiet --upgrade mlx-whisper
"$DIR/venv/bin/python" -c "import mlx_whisper" || die "mlx-whisper import failed"
echo "  mlx-whisper: $("$DIR/venv/bin/python" -m pip show mlx-whisper 2>/dev/null | awk '/^Version/{print $2}')"

say "Downloading the joiner agent (sha256-verified against $BASE/join/agent.json)"
curl -fsSL "$BASE/join/agent.py" -o "$DIR/agent.py.new"
WANT_SHA="$(curl -fsSL "$BASE/join/agent.json" | "$DIR/venv/bin/python" -c 'import json,sys;print(json.load(sys.stdin)["sha256"])')"
GOT_SHA="$(shasum -a 256 "$DIR/agent.py.new" | awk '{print $1}')"
[ "$WANT_SHA" = "$GOT_SHA" ] || die "agent.py checksum mismatch (want $WANT_SHA got $GOT_SHA)"
"$DIR/venv/bin/python" -m py_compile "$DIR/agent.py.new"
mv "$DIR/agent.py.new" "$DIR/agent.py"
chmod +x "$DIR/agent.py"
echo "  $DIR/agent.py"

say "Checking for the telemetry token"
if [ ! -s "$TOKEN_FILE" ]; then
  cat <<EOF

  The telemetry token is NOT on this Mac yet ($TOKEN_FILE).
  It is never published. Copy it from the existing team Mac (the one already running lanes):
    - AirDrop:  on that Mac, AirDrop ~/.secrets/capreg-telemetry-token to this Mac, then
                mkdir -p ~/.secrets && mv ~/Downloads/capreg-telemetry-token ~/.secrets/ && chmod 600 ~/.secrets/capreg-telemetry-token
    - LAN scp:  mkdir -p ~/.secrets && scp <user>@<that-mac>.local:.secrets/capreg-telemetry-token ~/.secrets/ && chmod 600 ~/.secrets/capreg-telemetry-token
  Then re-run this script.
EOF
  exit 3
fi
chmod 600 "$TOKEN_FILE"
echo "  token file present (not printed)"

if [ "${CAPREG_SKIP_SELFTEST:-0}" != "1" ]; then
  say "Self-test: dry-run claim (no lease) + 60 s download and mlx-whisper decode (no upload)"
  echo "  First run downloads the turbo model (~1.6 GB) from Hugging Face."
  "$DIR/venv/bin/python" "$DIR/agent.py" --self-test --host-label "$HOST_LABEL" || die "self-test failed; see output above"
fi

if [ "$WITH_OCR" = "1" ]; then
  say "Installing the meeting-docs OCR lane (launchd; lanes follow $BASE/hosts/$HOST_LABEL/config)"
  curl -fsSL "https://meeting-docs.canalandcountry.workers.dev/join/ocr-bootstrap.sh" | bash -s -- "$HOST_LABEL" || echo "  OCR lane install failed (ASR is unaffected); see output above"
fi

say "Ready. Start the lanes (keep the Mac on power, lid open):"
cat <<EOF

  cd "$DIR" && caffeinate -dimsu "$DIR/venv/bin/python" "$DIR/agent.py" --host-label $HOST_LABEL

  Optional: --region mid-hudson|rochester|capital-region   --prefetch 3   --buffer-ahead 6
  Remote control: lanes, home lane and OCR lanes come from $BASE/hosts/$HOST_LABEL/config; the agent
  self-updates and starts the OCR lane on its own (--no-self-update / --no-ocr to opt out).
  YouTube stays OFF on this host (shared IP). Only the operator turns it on (--allow-youtube).
  Run it in a terminal tab you keep open, or under tmux. Ctrl-C releases leases and exits cleanly.
  Local log: $DIR/agent.log      Team page: $BASE/join      Status: $BASE/status
EOF
