#!/bin/sh
# Installs the Academic Support data source skill for Claude Code (macOS, Linux, WSL, Git Bash).
#   curl -fsSL https://insights.alpha.school/skill/academic-support/install.sh | sh
# Downloads the pack into ~/.claude/skills/academic-support (replacing an earlier copy), asks once for your API key and keeps it in
# ~/.claude/academic-support-api.env (mode 600, never inside the skill folder), then runs the pack check and the smoke test.
# Non-interactive: set ACADEMIC_SUPPORT_API_KEY (or TIMEBACK_CLIENT_ID and TIMEBACK_CLIENT_SECRET, with TimeBack admin access) in the environment; CLAUDE_SKILLS_DIR overrides the skills folder.
# The whole script is one function called on the last line, so a download cut short runs nothing.
set -eu

main() {
  ORIGIN='https://insights.alpha.school'
  NAME='academic-support'
  API_URL_DEFAULT='https://4cnfu40x26.execute-api.us-east-1.amazonaws.com/prod'
  SKILLS="${CLAUDE_SKILLS_DIR:-$HOME/.claude/skills}"
  ENV_FILE="$HOME/.claude/$NAME-api.env"

  command -v curl >/dev/null 2>&1 || die "curl is required"
  command -v tar >/dev/null 2>&1 || die "tar is required"
  TMP=$(mktemp -d 2>/dev/null || mktemp -d -t "$NAME")
  trap 'restore_tty; rm -rf "$TMP"' EXIT
  trap 'exit 130' INT TERM

  step "1/3  Downloading the Academic Support skill"
  curl -fsSL "$ORIGIN/skill/$NAME/download/$NAME.tar.gz" -o "$TMP/pack.tar.gz" || die "download failed"
  mkdir -p "$TMP/x" && tar -xzf "$TMP/pack.tar.gz" -C "$TMP/x" || die "the download is not a valid archive"
  [ -f "$TMP/x/$NAME/SKILL.md" ] || die "the archive has no $NAME/SKILL.md"
  mkdir -p "$SKILLS"
  rm -rf "$SKILLS/$NAME"
  mv "$TMP/x/$NAME" "$SKILLS/$NAME"
  say "   installed in $SKILLS/$NAME"

  step "2/3  API key or TimeBack credentials"
  if [ -f "$ENV_FILE" ] && [ -z "${ACADEMIC_SUPPORT_API_KEY:-}" ] && [ -z "${TIMEBACK_CLIENT_ID:-}" ]; then
    say "   keeping your existing $ENV_FILE"
  else
    KEY="${ACADEMIC_SUPPORT_API_KEY:-}"
    [ -n "$KEY" ] || ask KEY "   Paste your API key (hidden; Enter to skip or to use your TimeBack client ID and secret): " 1
    TB_ID=''; TB_SECRET=''
    if [ -z "$KEY" ]; then
      TB_ID="${TIMEBACK_CLIENT_ID:-}"; TB_SECRET="${TIMEBACK_CLIENT_SECRET:-}"
      [ -n "$TB_ID" ] || ask TB_ID "   TimeBack client ID (Enter to skip): " 0
      [ -z "$TB_ID" ] || [ -n "$TB_SECRET" ] || ask TB_SECRET "   TimeBack client secret (hidden): " 1
    fi
    URL="${ACADEMIC_SUPPORT_API_URL:-$API_URL_DEFAULT}"
    [ -n "$URL" ] || ask URL "   API base URL: " 0
    if [ -n "$URL" ] && { [ -n "$KEY" ] || { [ -n "$TB_ID" ] && [ -n "$TB_SECRET" ]; }; }; then
      mkdir -p "$HOME/.claude"
      rm -f "$ENV_FILE"   # a new file, so the umask below decides its mode (an old 0644 file would keep 0644)
      if [ -n "$KEY" ]; then
        ( umask 077 && printf 'ACADEMIC_SUPPORT_API_URL=%s\nACADEMIC_SUPPORT_API_KEY=%s\n' "$URL" "$KEY" > "$ENV_FILE" )
      else
        ( umask 077 && printf 'ACADEMIC_SUPPORT_API_URL=%s\nTIMEBACK_CLIENT_ID=%s\nTIMEBACK_CLIENT_SECRET=%s\n' "$URL" "$TB_ID" "$TB_SECRET" > "$ENV_FILE" )
      fi
      chmod 600 "$ENV_FILE"
      say "   saved to $ENV_FILE (only you can read it)"
    else
      say "   skipped — create $ENV_FILE later (see https://insights.alpha.school/skill/$NAME)"
    fi
  fi

  step "3/3  Checks"
  PY=$(find_python)
  if [ -z "$PY" ]; then
    say "   Python 3 not found — skipping the checks (the skill itself does not need it)"
  else
    (cd "$SKILLS/$NAME" && "$PY" datasource/pack_check.py --quiet >/dev/null) || die "the pack check failed"
    if [ -f "$ENV_FILE" ]; then
      say "   running the smoke test against the API (a minute or two)…"
      (cd "$SKILLS/$NAME" && "$PY" datasource/smoke.py 2>/dev/null) || say "   the smoke test did not pass — check the credentials in $ENV_FILE and run: $PY $SKILLS/$NAME/datasource/smoke.py"
    fi
  fi

  printf '\n\033[32mDone.\033[0m Open Claude Code and ask, for example:\n  "%s"\n' 'Using the academic-support skill, how many students at <campus> are held back by a problem the system should have caught, and how many have no one working on it?'
}

say() { printf '%s\n' "$*"; }
step() { printf '\n\033[1m%s\033[0m\n' "$*"; }
die() { printf '\033[31merror:\033[0m %s\n' "$*" >&2; exit 1; }
has_tty() { ( : < /dev/tty ) 2>/dev/null; }   # a terminal we can open (Claude Code and CI have none)
TTY_HIDDEN=
restore_tty() { if [ -n "$TTY_HIDDEN" ]; then stty echo < /dev/tty 2>/dev/null || true; TTY_HIDDEN=; fi; }
ask() { # ask <variable> <prompt> <hidden:0|1>: read from the terminal even when the script is piped; empty without one
  _v=''
  if has_tty; then
    printf '%s' "$2" > /dev/tty
    if [ "$3" = 1 ]; then TTY_HIDDEN=1; stty -echo < /dev/tty 2>/dev/null || true; fi
    IFS= read -r _v < /dev/tty || _v=''
    if [ "$3" = 1 ]; then restore_tty; printf '\n' > /dev/tty; fi
  fi
  eval "$1=\$_v"
}
find_python() { # a Python 3.8+ that actually runs (macOS ships a /usr/bin/python3 stub that only offers to install the developer tools)
  if [ "$(uname -s 2>/dev/null)" = Darwin ] && ! xcode-select -p >/dev/null 2>&1; then
    for c in /opt/homebrew/bin/python3 /usr/local/bin/python3; do [ -x "$c" ] && { printf '%s' "$c"; return 0; }; done
    return 0
  fi
  for c in python3 python; do
    if command -v "$c" >/dev/null 2>&1 && "$c" -c 'import sys; sys.exit(sys.version_info < (3, 8))' >/dev/null 2>&1; then printf '%s' "$c"; return 0; fi
  done
}

main "$@"
