#!/usr/bin/env bash
# Gorg for Claude Code: installs the video tools and the editing skills on this Mac, and connects Claude Code to
# your Gorg account. Run it again any time to update. Nothing here needs sudo.
#
#   curl -fsSL https://www.gorg.ai/gorg/install.sh | bash
set -euo pipefail

BASE="${GORG_BASE:-https://www.gorg.ai}"
HOME_DIR="${GORG_HOME:-$HOME/.gorg}"
SKILLS_DIR="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/skills"
MODEL="ggml-large-v3-turbo-q5_0.bin"
MODEL_URL="https://huggingface.co/ggerganov/whisper.cpp/resolve/main/$MODEL"

say() { printf '\n\033[1m%s\033[0m\n' "$1"; }
note() { printf '  %s\n' "$1"; }
stop() { printf '\n\033[31m%s\033[0m\n' "$1" >&2; exit 1; }
have() { command -v "$1" >/dev/null 2>&1; }

# Everything runs inside main, called on the last line, so a half-downloaded script does nothing; and every tool
# reads from /dev/null, so none of them can swallow the rest of this script when it is piped into bash.
main() {
  [ "$(uname -s)" = "Darwin" ] || stop "Gorg for Claude Code runs on a Mac for now."
  have claude || stop "Claude Code is not installed. Get it at https://claude.com/claude-code and run this again."
  have brew || stop "Homebrew is not installed. Get it at https://brew.sh and run this again."

  mkdir -p "$HOME_DIR/models" "$SKILLS_DIR"
  WORK="$(mktemp -d)"
  trap 'rm -rf "$WORK"' EXIT

  say "1/7 Video tools"
  for pair in ffmpeg:ffmpeg whisper-cli:whisper-cpp node:node python3:python; do
    bin="${pair%%:*}"; formula="${pair##*:}"
    if have "$bin"; then note "$bin is here"; else note "installing $formula"; brew install --quiet "$formula"; fi
  done

  say "2/7 Speech model (574 MB, once)"
  if [ -s "$HOME_DIR/models/$MODEL" ]; then note "already downloaded"
  else curl -fL --progress-bar -o "$WORK/$MODEL" "$MODEL_URL" && mv "$WORK/$MODEL" "$HOME_DIR/models/$MODEL"; fi

  say "3/7 Tesseract and HyperFrames"
  npx -y skills add mirage-hq/tesseract -g -y -a claude-code -s tesseract-video -s tesseract-motion >/dev/null
  npx -y skills add heygen-com/hyperframes -g -y -a claude-code -s hyperframes -s hyperframes-cli -s hyperframes-registry -s media-use -s reverse-any-video >/dev/null
  note "skills added"
  if have hyperframes; then note "hyperframes is here"; else npm install -g --silent hyperframes && note "hyperframes installed"; fi
  hyperframes browser ensure >/dev/null 2>&1 || note "HyperFrames will fetch its browser on first render"

  # The Tesseract skill pins the CLI version it was written for; install exactly that one.
  PIN_FILE="$SKILLS_DIR/tesseract-video/references/cli-version.txt"
  [ -s "$PIN_FILE" ] || stop "The Tesseract skill did not install. Run this again; if it repeats, tell us at $BASE."
  PIN="$(tr -d '[:space:]' < "$PIN_FILE")"
  TSRCT="$HOME/Library/Application Support/Tesseract/bin/tsrct"
  if [ -x "$TSRCT" ] && "$TSRCT" --version 2>/dev/null | grep -q "tsrct $PIN "; then note "tsrct $PIN is here"
  else
    case "$(uname -m)" in arm64) ARCH=arm64 ;; *) [ "$(sysctl -in sysctl.proc_translated 2>/dev/null)" = "1" ] && ARCH=arm64 || ARCH=x86_64 ;; esac
    ZIP="tesseract-$PIN-darwin-$ARCH.zip"
    REL="https://github.com/mirage-hq/tesseract/releases/download/v$PIN"
    ( cd "$WORK" && curl -fsSLO "$REL/$ZIP" && curl -fsSLO "$REL/$ZIP.sha256" && shasum -a 256 -c "$ZIP.sha256" >/dev/null ) || stop "Tesseract $PIN did not download or its checksum did not match."
    ditto -x -k "$WORK/$ZIP" "$WORK/tesseract"
    bash "$(find "$WORK/tesseract" -name install.sh -maxdepth 3 | head -1)" >/dev/null
    note "tsrct $PIN installed"
  fi

  say "4/7 Gorg's editing skills"
  ( cd "$WORK" && curl -fsSLO "$BASE/gorg/skills.tgz" && curl -fsSLO "$BASE/gorg/skills.tgz.sha256" && shasum -a 256 -c skills.tgz.sha256 >/dev/null ) || stop "Gorg's skills did not download or their checksum did not match."
  mkdir "$WORK/skills" && tar -xzf "$WORK/skills.tgz" -C "$WORK/skills"
  for dir in "$WORK"/skills/*/; do
    name="$(basename "$dir")"
    rm -rf "${SKILLS_DIR:?}/$name" && cp -R "$dir" "$SKILLS_DIR/$name" && note "$name"
  done

  say "5/7 Python for the cutting and caption scripts"
  [ -x "$HOME_DIR/venv/bin/python" ] || python3 -m venv "$HOME_DIR/venv"
  "$HOME_DIR/venv/bin/pip" install --quiet --upgrade pip
  "$HOME_DIR/venv/bin/pip" install --quiet -r "$SKILLS_DIR/video-editing/scripts/requirements.txt"
  note "ready at $HOME_DIR/venv"

  say "6/7 Your Gorg account"
  if claude mcp get gorg >/dev/null 2>&1; then note "already connected"
  else claude mcp add --transport http --scope user gorg "$BASE/api/studio/mcp" >/dev/null && note "added"; fi

  say "7/7 The helper that makes the videos you text Gorg"
  mkdir -p "$HOME_DIR/bin"
  ( cd "$WORK" && curl -fsSLO "$BASE/gorg/gorg-helper.mjs" && curl -fsSLO "$BASE/gorg/gorg-helper.mjs.sha256" && shasum -a 256 -c gorg-helper.mjs.sha256 >/dev/null ) || stop "Gorg's helper did not download or its checksum did not match."
  cp "$WORK/gorg-helper.mjs" "$HOME_DIR/bin/gorg-helper.mjs"
  PLIST="$HOME/Library/LaunchAgents/ai.gorg.helper.plist"
  mkdir -p "$(dirname "$PLIST")"
  # launchd starts with a bare PATH: give the helper the one this shell has, so it finds claude, ffmpeg and node.
  cat > "$PLIST" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>ai.gorg.helper</string>
  <key>ProgramArguments</key><array><string>$(command -v node)</string><string>$HOME_DIR/bin/gorg-helper.mjs</string></array>
  <key>EnvironmentVariables</key><dict>
    <key>PATH</key><string>$PATH</string>
    <key>HOME</key><string>$HOME</string>
    <key>GORG_HOME</key><string>$HOME_DIR</string>
    <key>GORG_BASE</key><string>$BASE</string>
    <key>GORG_CLAUDE</key><string>$(command -v claude)</string>
  </dict>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>ThrottleInterval</key><integer>30</integer>
  <key>StandardOutPath</key><string>$HOME_DIR/helper.log</string>
  <key>StandardErrorPath</key><string>$HOME_DIR/helper.log</string>
</dict></plist>
PLIST
  if [ "${GORG_NO_LAUNCH:-}" = "1" ]; then note "installed, not started"
  else
    # Stopping is not instant: starting again before the old one is gone fails, and the helper would be left off.
    launchctl bootout "gui/$(id -u)/ai.gorg.helper" >/dev/null 2>&1 || true
    for _ in 1 2 3 4 5 6 7 8 9 10; do launchctl print "gui/$(id -u)/ai.gorg.helper" >/dev/null 2>&1 || break; sleep 1; done
    for _ in 1 2 3; do launchctl bootstrap "gui/$(id -u)" "$PLIST" >/dev/null 2>&1 && break; sleep 2; done
    launchctl print "gui/$(id -u)/ai.gorg.helper" >/dev/null 2>&1 || stop "The helper did not start. Run this again; if it repeats, tell us at $BASE."
    note "running; its log is $HOME_DIR/helper.log"
  fi

  cat <<EOF

Done. Open Claude Code in a folder with your clips and type:

  /mcp            sign in to Gorg once (it opens your browser)
  /gorg           then say what video you want

After that first /gorg, videos you text Gorg are made on this Mac while it is awake,
and Gorg texts you when each one is ready. To stop that: launchctl bootout gui/$(id -u)/ai.gorg.helper

EOF
}

main </dev/null
