#!/usr/bin/env bash
#
# A wizard — walks a human through a manual procedure step by step.
# Generated by the /wizard skill.
#
# Everything above the "STAGES" marker is the wizard library: do not hand-edit
# it. Author the per-step stages below the marker.

set -euo pipefail

# ──────────────────────────────────────────────────────────────────────────
# Wizard library — delightful, consistent UX. Identical across every wizard.
# ──────────────────────────────────────────────────────────────────────────

if [[ -t 1 ]] && command -v tput >/dev/null 2>&1 && [[ "$(tput colors 2>/dev/null || echo 0)" -ge 8 ]]; then
  BOLD=$(tput bold); DIM=$(tput dim); RESET=$(tput sgr0)
  BLUE=$(tput setaf 4); GREEN=$(tput setaf 2); YELLOW=$(tput setaf 3); RED=$(tput setaf 1)
else
  BOLD=""; DIM=""; RESET=""; BLUE=""; GREEN=""; YELLOW=""; RED=""
fi

# Author sets these two at the top of the stages section.
TOTAL_STAGES=0
TOTAL_MINUTES=0

_STAGE_INDEX=0
_MINUTES_ELAPSED=0
ENV_FILE="${ENV_FILE:-.env}"
WRITTEN_ENV=()    # KEYs written to ENV_FILE this run
WRITTEN_SECRET=() # secret NAMEs set this run
SKIPPED=()        # things we couldn't do (e.g. gh missing)

# _clear — wipe the terminal so only the current step is on screen. No-op when
# output isn't a terminal, so piped logs stay readable.
_clear() {
  [[ -t 1 ]] || return 0
  if command -v tput >/dev/null 2>&1; then tput clear; else printf '\033[2J\033[3J\033[H'; fi
}

# banner "Title" — opening frame: what this wizard does and how long it takes.
banner() {
  _clear
  printf '\n%s%s  %s%s\n' "$BOLD" "$BLUE" "$1" "$RESET"
  printf '%s  %s stages · about %s minutes%s\n\n' \
    "$DIM" "$TOTAL_STAGES" "$TOTAL_MINUTES" "$RESET"
  printf '%s  You drive the browser; this wizard tells you exactly what to do and\n' "$DIM"
  printf '  captures the values you copy back. Stop any time with Ctrl-C and re-run\n'
  printf '  later — it remembers values already saved.%s\n' "$RESET"
  pause "Ready to start?"
}

# stage "Name" <minutes> — clear the screen, then announce a stage and show
# progress + time remaining. Clearing keeps only the current step on screen.
stage() {
  _clear
  _STAGE_INDEX=$((_STAGE_INDEX + 1))
  local remaining=$((TOTAL_MINUTES - _MINUTES_ELAPSED))
  (( remaining < 0 )) && remaining=0
  _MINUTES_ELAPSED=$((_MINUTES_ELAPSED + ${2:-0}))
  printf '\n%s%s▸ Stage %s/%s · %s%s  %s(~%s min left)%s\n' \
    "$BOLD" "$BLUE" "$_STAGE_INDEX" "$TOTAL_STAGES" "$1" "$RESET" "$DIM" "$remaining" "$RESET"
}

# say "..." — a plain instruction line.
say()  { printf '  %s\n' "$1"; }
# step "..." — a numbered-feeling action the human takes in the browser.
step() { printf '  %s•%s %s\n' "$BLUE" "$RESET" "$1"; }
note() { printf '  %s%s%s\n' "$DIM" "$1" "$RESET"; }
warn() { printf '  %s⚠ %s%s\n' "$YELLOW" "$1" "$RESET"; }

# open_url URL — open in the human's browser, cross-platform incl. WSL.
open_url() {
  local url="$1"
  printf '  %s↗ opening%s %s\n' "$GREEN" "$RESET" "$url"
  { if   command -v wslview     >/dev/null 2>&1; then wslview "$url"
    elif command -v explorer.exe >/dev/null 2>&1; then explorer.exe "$url"
    elif command -v xdg-open    >/dev/null 2>&1; then xdg-open "$url"
    elif command -v open        >/dev/null 2>&1; then open "$url"
    else warn "couldn't open a browser — visit it manually: $url"; fi
  } >/dev/null 2>&1 || warn "couldn't open a browser — visit it manually: $url"
}

# pause "msg" — wait for the human to confirm they've done the manual part.
pause() {
  printf '  %s%s%s ' "$DIM" "${1:-Press Enter to continue}" "$RESET"
  read -r _ || true
}

# confirm "question" — y/N gate; returns success on yes.
confirm() {
  local reply=""
  printf '  %s? %s [y/N] ' "$YELLOW" "$1"
  read -r reply || true
  [[ "$reply" =~ ^[Yy] ]]
}

# _existing KEY — current value of KEY in ENV_FILE, if any.
_existing() {
  [[ -f "$ENV_FILE" ]] || return 1
  local line; line=$(grep -E "^${1}=" "$ENV_FILE" | tail -n1) || return 1
  printf '%s' "${line#*=}"
}

# ask KEY "Prompt" — read a value into $KEY. Offers the existing .env value as
# a default on re-runs (Enter keeps it). Visible input (non-secret).
ask() {
  local key="$1" prompt="$2" current input
  current=$(_existing "$key" || true)
  if [[ -n "$current" ]]; then
    printf '  %s%s%s %s[Enter keeps current]%s ' "$BOLD" "$prompt" "$RESET" "$DIM" "$RESET"
  else
    printf '  %s%s%s ' "$BOLD" "$prompt" "$RESET"
  fi
  read -r input || true
  [[ -z "$input" && -n "$current" ]] && input="$current"
  printf -v "$key" '%s' "$input"
}

# ask_secret KEY "Prompt" — like ask, but input is hidden.
ask_secret() {
  local key="$1" prompt="$2" current input
  current=$(_existing "$key" || true)
  if [[ -n "$current" ]]; then
    printf '  %s%s%s %s[Enter keeps current]%s ' "$BOLD" "$prompt" "$RESET" "$DIM" "$RESET"
  else
    printf '  %s%s%s ' "$BOLD" "$prompt" "$RESET"
  fi
  read -rs input || true
  printf '\n'
  [[ -z "$input" && -n "$current" ]] && input="$current"
  printf -v "$key" '%s' "$input"
}

# write_env KEY VALUE — upsert KEY=VALUE into ENV_FILE (creates it; replaces
# any existing line). Idempotent.
write_env() {
  local key="$1" value="$2" tmp
  touch "$ENV_FILE"
  tmp=$(mktemp)
  grep -vE "^${key}=" "$ENV_FILE" > "$tmp" || true
  printf '%s=%s\n' "$key" "$value" >> "$tmp"
  mv "$tmp" "$ENV_FILE"
  WRITTEN_ENV+=("$key")
  printf '  %s✓ wrote%s %s → %s\n' "$GREEN" "$RESET" "$key" "$ENV_FILE"
}

# set_secret NAME VALUE — set a GitHub Actions repo secret via gh. Falls back
# to a warning (and records it) if gh is unavailable or unauthenticated.
set_secret() {
  local name="$1" value="$2"
  if command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; then
    if printf '%s' "$value" | gh secret set "$name" >/dev/null 2>&1; then
      WRITTEN_SECRET+=("$name")
      printf '  %s✓ set%s GitHub secret %s\n' "$GREEN" "$RESET" "$name"
      return
    fi
  fi
  SKIPPED+=("GitHub secret $name (set it manually: gh secret set $name)")
  warn "skipped GitHub secret $name — gh not ready; set it later"
}

# set_var NAME VALUE — set a GitHub Actions repo variable (non-secret).
set_var() {
  local name="$1" value="$2"
  if command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; then
    if gh variable set "$name" --body "$value" >/dev/null 2>&1; then
      printf '  %s✓ set%s GitHub variable %s\n' "$GREEN" "$RESET" "$name"
      return
    fi
  fi
  SKIPPED+=("GitHub variable $name")
  warn "skipped GitHub variable $name — gh not ready; set it later"
}

# finish — clear, then a closing summary of everything configured.
finish() {
  _clear
  printf '\n%s%s  ✓ Setup complete%s\n' "$BOLD" "$GREEN" "$RESET"
  (( ${#WRITTEN_ENV[@]} ))    && note "wrote ${#WRITTEN_ENV[@]} value(s) to $ENV_FILE: ${WRITTEN_ENV[*]}"
  (( ${#WRITTEN_SECRET[@]} )) && note "set ${#WRITTEN_SECRET[@]} GitHub secret(s): ${WRITTEN_SECRET[*]}"
  if (( ${#SKIPPED[@]} )); then
    printf '\n'; warn "still to do by hand:"
    for s in "${SKIPPED[@]}"; do note "  - $s"; done
  fi
  printf '\n'
}

# ──────────────────────────────────────────────────────────────────────────
# STAGES — author this section. One stage() per step the human takes.
# Replace the example below. Set the two totals to match the stages you write.
# ──────────────────────────────────────────────────────────────────────────

TOTAL_STAGES=5
TOTAL_MINUTES=12

# This wizard configures CVM's .env and DB, wherever the wizard is run from.
CVM_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="$CVM_DIR/.env"
REDIRECT_URI="http://localhost:5173/api/auth/dropbox/callback"

# strip_env KEY — remove any line for KEY from ENV_FILE (for retiring a var).
strip_env() {
  local key="$1" tmp
  [[ -f "$ENV_FILE" ]] || return 0
  grep -qE "^${key}=" "$ENV_FILE" || return 0
  tmp=$(mktemp)
  grep -vE "^${key}=" "$ENV_FILE" > "$tmp" || true
  mv "$tmp" "$ENV_FILE"
  printf '  %s✓ removed%s deprecated %s from %s\n' "$GREEN" "$RESET" "$key" "$ENV_FILE"
}

banner "CVM Dropbox publish setup"

# ── Stage 1: create the Dropbox app and copy its credentials ───────────────
stage "Create the Dropbox app & copy credentials" 5
say "CVM now publishes to Dropbox over the HTTP API (PR #1419), so it needs its"
say "own Dropbox app instead of a synced folder. Let's create one."
open_url "https://www.dropbox.com/developers/apps/create"
step "Choose an API: 'Scoped access'."
step "Choose the access type: 'Full Dropbox' (courses live outside the app folder)."
step "Name the app (e.g. 'CVM Publish') and click Create app."
say ""
say "On the app's Settings tab, find the OAuth 2 section:"
step "In 'Redirect URIs', paste this exact URL and click Add:"
note "    $REDIRECT_URI"
warn "It must match exactly — Dropbox rejects the login otherwise."
say ""
step "Still on Settings, copy the 'App key' and reveal + copy the 'App secret'."
ask        DROPBOX_APP_KEY    "Paste the App key:"
ask_secret DROPBOX_APP_SECRET "Paste the App secret:"
write_env DROPBOX_APP_KEY    "$DROPBOX_APP_KEY"
write_env DROPBOX_APP_SECRET "$DROPBOX_APP_SECRET"
pause

# ── Stage 2: grant the app the scopes CVM uses ─────────────────────────────
stage "Grant the app its permissions (scopes)" 2
say "CVM uploads bundles, downloads receipts, and lists folders — enable those scopes."
step "Open the app's 'Permissions' tab (same app you just created)."
step "Tick these three scopes:"
note "    files.content.write   (upload course bundles)"
note "    files.content.read    (download the course.json receipt)"
note "    files.metadata.read   (get_metadata / list_folder)"
step "Click 'Submit' at the bottom to save the permissions."
warn "Set scopes BEFORE connecting in stage 5, or the token won't carry them."
pause "Done ticking + submitting the scopes?"

# ── Stage 3: point CVM at the remote path + retire the old vars ────────────
stage "Set the remote path & retire the old config" 2
say "DROPBOX_REMOTE_PATH is the folder path INSIDE your Dropbox account (not a"
say "local /mnt path). Your old DROPBOX_PATH was '/mnt/d/Dropbox/AI Hero/Courses',"
say "which is '/AI Hero/Courses' relative to the Dropbox root."
ask DROPBOX_REMOTE_PATH "Remote courses path [Enter for /AI Hero/Courses]:"
[[ -z "$DROPBOX_REMOTE_PATH" ]] && DROPBOX_REMOTE_PATH="/AI Hero/Courses"
write_env DROPBOX_REMOTE_PATH "$DROPBOX_REMOTE_PATH"
say ""
say "Retiring the deprecated variables from this transport's predecessor:"
strip_env DROPBOX_PATH        # renamed → DROPBOX_REMOTE_PATH
strip_env PUBLISH_STAGING_DIR # removed with the FS-transport staging machinery
pause

# ── Stage 4: run the DB migration for the token table ──────────────────────
stage "Run the dropbox_auth migration" 1
say "The OAuth tokens are stored in a new 'dropbox_auth' table (migration 0007)."
step "This runs: pnpm db:migrate   (in $CVM_DIR)"
if confirm "Run the migration now?"; then
  ( cd "$CVM_DIR" && pnpm db:migrate ) \
    && printf '  %s✓ migration applied%s\n' "$GREEN" "$RESET" \
    || { warn "migration failed — run 'pnpm db:migrate' by hand in $CVM_DIR"; \
         SKIPPED+=("run 'pnpm db:migrate' in $CVM_DIR"); }
else
  note "skipped — run 'pnpm db:migrate' yourself before publishing."
  SKIPPED+=("run 'pnpm db:migrate' in $CVM_DIR")
fi
pause

# ── Stage 5: connect the Dropbox account via OAuth ─────────────────────────
stage "Connect your Dropbox account (OAuth)" 2
say "Finally, authorize CVM against the app. This stores a refresh token in the DB."
step "In a separate terminal, start the dev server:  cd $CVM_DIR && pnpm dev"
pause "Press Enter once the server is up on http://localhost:5173"
say ""
say "Now kick off the OAuth flow (redirects to Dropbox, then back to CVM):"
open_url "http://localhost:5173/api/auth/dropbox/initiate"
step "Click 'Allow' on the Dropbox consent screen."
step "You'll be redirected back to CVM — that's the token being saved."
warn "If it bounces back with ?error=... the redirect URI or scopes don't match"
warn "the app — recheck stages 1 and 2."
pause "Did Dropbox redirect you back to CVM without an error?"

finish
