#!/bin/bash
# Fornace pi installer. Steps run in the foreground in one shell.
# Usage:
#   sh -c "$(curl -fsSL https://onboarding.fornace.app/install.sh)"
set -Eeuo pipefail

BASE="${PI_SETUP_BASE:-https://onboarding.fornace.app}"
PI_DIR="${PI_DIR:-${PI_CODING_AGENT_DIR:-$HOME/.pi/agent}}"
export PI_DIR
NODE_BIN="${FORNACE_NODE_BIN:-}"
PASSED_TOKEN="${FORNACE_TOKEN:-}"

while [ $# -gt 0 ]; do
  case "$1" in
    --token)
      [ $# -ge 2 ] || { echo "Error: --token requires a value"; exit 1; }
      PASSED_TOKEN="$2"; shift 2 ;;
    --token=*)
      PASSED_TOKEN="${1#--token=}"; shift ;;
    *)
      shift ;;
  esac
done

load_installer_helper() {
  local name="${1:-}" tmp
  case "$name" in
    install-ui.sh|install-runtimes.sh|install-workspace.sh|install-pi.sh) ;;
    *) printf 'FATAL: refused to load unexpected installer helper: <%s>\n' "$name" >&2; return 1 ;;
  esac
  tmp="${TMPDIR:-/tmp}/fornace-${name%.sh}-$$.sh"
  curl -fsSL "$BASE/$name" > "$tmp" || {
    printf 'FATAL: cannot fetch %s/%s\n' "$BASE" "$name" >&2
    rm -f "$tmp"
    return 1
  }
  [ -s "$tmp" ] || {
    printf 'FATAL: downloaded installer helper %s is empty\n' "$name" >&2
    rm -f "$tmp"
    return 1
  }
  # shellcheck disable=SC1090
  . "$tmp"
  rm -f "$tmp"
}

load_installer_helper install-ui.sh

if [ "$(uname -s)" != "Darwin" ]; then
  echo "Error: macOS required."
  exit 1
fi

if [ "$(id -u)" -eq 0 ]; then
  printf '\n%sERROR: Do not run this installer with sudo or as root.%s\n' "$C_RED" "$C_RESET" >&2
  printf 'The Fornace environment is strictly user-space and installs to ~/.pi/agent.\n' >&2
  printf 'Homebrew and npm will fail or corrupt permissions if run as root.\n' >&2
  printf 'Please run as your standard macOS user account:\n' >&2
  printf '  sh -c "$(curl -fsSL https://onboarding.fornace.app/install.sh)"\n\n' >&2
  exit 1
fi

export PATH="$HOME/.local/bin:$PATH"

macos_ver="$(sw_vers -productVersion)"
macos_major="$(echo "$macos_ver" | cut -d. -f1)"
arch="$(uname -m)"
[ "$arch" = "arm64" ] && arch_desc="Apple Silicon" || arch_desc="Intel"

if [ "$UI_TTY" = 1 ]; then
  hide="${ESC_CHAR}[?25l"
  show="${ESC_CHAR}[?25h"
  printf '%s' "$hide"

  logo_l1="   ███████╗ ██████╗ ██████╗ ███╗   ██╗  █████╗  ██████╗███████╗"
  logo_l2="   ██╔════╝██╔═══██╗██╔══██╗████╗  ██║ ██╔══██╗██╔════╝██╔════╝"
  logo_l3="   █████╗  ██║   ██║██████╔╝██╔██╗ ██║ ███████║██║     █████╗  "
  logo_l4="   ██╔══╝  ██║   ██║██╔══██╗██║╚██╗██║ ██╔══██║██║     ██╔══╝  "
  logo_l5="   ██║     ╚██████╔╝██║  ██║██║ ╚████║ ██║  ██║╚██████╗███████╗"
  logo_l6="   ╚═╝      ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═══╝ ╚═╝  ╚═╝ ╚═════╝╚══════╝"

  # Phosphor CRT warm-up scan: dark -> dim -> bright flash -> settle into full official rainbow
  printf '%s' "$SYNC_ON"
  for phase in "$C_DARK" "$C_DIM" "$C_GREEN"; do
    printf '%s%s\n%s\n%s\n%s\n%s\n%s%s\n\n' "$phase" \
      "$logo_l1" "$logo_l2" "$logo_l3" "$logo_l4" "$logo_l5" "$logo_l6" "$C_RESET"
    sleep 0.08
    printf '%s[7A' "$ESC_CHAR"
  done

  # Official Fornace Rainbow Logo (letters in Yellow, Orange, Red, Magenta, Indigo, Blue, Green)
  if [ -n "$CLR_F" ]; then
    rb_l1="   ${CLR_F}███████╗${C_RESET} ${CLR_O}██████╗ ${C_RESET} ${CLR_R}██████╗ ${C_RESET} ${CLR_N}███╗   ██╗${C_RESET} ${CLR_A} █████╗ ${C_RESET} ${CLR_C} ██████╗${C_RESET} ${CLR_E}███████╗${C_RESET}"
    rb_l2="   ${CLR_F}██╔════╝${C_RESET} ${CLR_O}██╔═══██╗${C_RESET} ${CLR_R}██╔══██╗${C_RESET} ${CLR_N}████╗  ██║${C_RESET} ${CLR_A}██╔══██╗${C_RESET} ${CLR_C}██╔════╝${C_RESET} ${CLR_E}██╔════╝${C_RESET}"
    rb_l3="   ${CLR_F}█████╗  ${C_RESET} ${CLR_O}██║   ██║${C_RESET} ${CLR_R}██████╔╝${C_RESET} ${CLR_N}██╔██╗ ██║${C_RESET} ${CLR_A}███████║${C_RESET} ${CLR_C}██║     ${C_RESET} ${CLR_E}█████╗  ${C_RESET}"
    rb_l4="   ${CLR_F}██╔══╝  ${C_RESET} ${CLR_O}██║   ██║${C_RESET} ${CLR_R}██╔══██╗${C_RESET} ${CLR_N}██║╚██╗██║${C_RESET} ${CLR_A}██╔══██║${C_RESET} ${CLR_C}██║     ${C_RESET} ${CLR_E}██╔══╝  ${C_RESET}"
    rb_l5="   ${CLR_F}██║     ${C_RESET} ${CLR_O}╚██████╔╝${C_RESET} ${CLR_R}██║  ██║${C_RESET} ${CLR_N}██║ ╚████║${C_RESET} ${CLR_A}██║  ██║${C_RESET} ${CLR_C}╚██████╗${C_RESET} ${CLR_E}███████╗${C_RESET}"
    rb_l6="   ${CLR_F}╚═╝     ${C_RESET} ${CLR_O} ╚═════╝ ${C_RESET} ${CLR_R}╚═╝  ╚═╝${C_RESET} ${CLR_N}╚═╝  ╚═══╝${C_RESET} ${CLR_A}╚═╝  ╚═╝${C_RESET} ${CLR_C} ╚═════╝${C_RESET} ${CLR_E}╚══════╝${C_RESET}"
    printf '%s\n%s\n%s\n%s\n%s\n%s\n\n' \
      "$rb_l1" "$rb_l2" "$rb_l3" "$rb_l4" "$rb_l5" "$rb_l6"
  else
    printf '%s%s\n%s\n%s\n%s\n%s\n%s%s\n\n' "$C_INK" \
      "$logo_l1" "$logo_l2" "$logo_l3" "$logo_l4" "$logo_l5" "$logo_l6" "$C_RESET"
  fi
  printf '%s' "$SYNC_OFF"

  printf '   %s%sFornace Workstation%s\n' "$C_BOLD" "$C_GREEN" "$C_RESET"
  printf '   %sThis sets up everything for you. It takes about 5 to 10 minutes.%s\n' "$C_INK" "$C_RESET"
  printf '   %sIt is safe to leave running. There are 4 steps and progress is shown as it goes.%s\n\n' "$C_DIM" "$C_RESET"
  printf '   %smacOS %s · %s%s\n' "$C_DARK" "$macos_ver" "$arch_desc" "$C_RESET"
  printf '   %sInstalling to %s%s\n\n' "$C_DARK" "$PI_DIR" "$C_RESET"
  printf '%s' "$show"
else
  printf '\n  Fornace Workstation setup\n'
  printf '  This sets up everything for you. It takes about 5 to 10 minutes.\n'
  printf '  macOS %s · %s · installing to %s\n' "$macos_ver" "$arch_desc" "$PI_DIR"
fi

mkdir -p "$PI_DIR"

load_installer_helper install-runtimes.sh

# 2. Token
section_header "2 of 4" "Connecting your account"

FINAL_TOKEN="$PASSED_TOKEN"
if [ -z "$FINAL_TOKEN" ] && [ -f "$PI_DIR/auth.json" ]; then
  FINAL_TOKEN="$(node -e '
    try {
      const a = JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"));
      process.stdout.write((a.mantice && a.mantice.key) || (a.fornace && a.fornace.key) || "");
    } catch(e) {}
  ' "$PI_DIR/auth.json" 2>/dev/null || true)"
fi

if [ -n "$FINAL_TOKEN" ]; then
  step_skip "Fornace Token" "existing key retained"
else
  if [ -t 0 ] && [ -r /dev/tty ]; then
    printf "    %sNo gateway token detected.%s Get your key on Telegram from %s@fornaceaibot%s (send %s/key%s)\n" "$C_YELLOW" "$C_RESET" "$C_BOLD$C_CYAN" "$C_RESET" "$C_BOLD" "$C_RESET"
    printf "    Paste token (or press Enter to configure later via Matchbox): "
    read -r input_tok < /dev/tty || input_tok=""
    input_tok="$(echo "$input_tok" | tr -d '[:space:]')"
    if [ -n "$input_tok" ]; then
      FINAL_TOKEN="$input_tok"
      step_skip "Fornace Token" "configured"
    else
      step_skip "Fornace Token" "skipped (set later with @fornaceaibot /key)"
    fi
  else
    step_skip "Fornace Token" "skipped"
  fi
fi

load_installer_helper install-workspace.sh

# 4. Verification & Team Access
section_header "4 of 4" "Checking everything works"

run_step "Verifying tools" "Checking your tools" node "$HOME/.local/lib/fornace/verify-runtime.mjs"
MATCHBOX_READY=0
MATCHBOX_DIR="${FORNACE_MATCHBOX_DIR:-$HOME/.config/fornace-matchbox}"
if [ -z "${FORNACE_MATCHBOX_DIR:-}" ] && [ ! -d "$MATCHBOX_DIR" ] && [ -d "$HOME/.config/fornace-broker" ]; then
  MATCHBOX_DIR="$HOME/.config/fornace-broker"
fi
if [ -f "$MATCHBOX_DIR/device.json" ]; then
  run_step "Verifying Matchbox" "Checking your team access" sh -c 'fornace-matchbox session >/dev/null'
  MATCHBOX_READY=1
elif [ -t 0 ] && [ -t 1 ] && [ "${FORNACE_NONINTERACTIVE:-0}" != 1 ]; then
  run_visible "Signing into Matchbox" "Signing this Mac into your team (a browser window will open)" fornace-matchbox login
  MATCHBOX_READY=1
else
  printf '    %s[..]%s Matchbox access: sign in with browser (%sfornace-matchbox login%s)\n' "$C_YELLOW" "$C_RESET" "$C_BOLD" "$C_RESET"
fi

if [ "$UI_TTY" = 1 ]; then
  rule="${C_DARK}------------------------------------------------------------${C_RESET}"
  printf '\n  %s\n' "$rule"
  printf '  %s%sYou are all set.%s\n' "$C_BOLD" "$C_GREEN" "$C_RESET"
  printf '  %s\n' "$rule"
  printf '\n  %sDo this next:%s\n\n' "$C_BOLD$C_INK" "$C_RESET"

  printf '  %s1.%s Open the cmux terminal.       %sopen -a cmux%s\n' "$C_GREEN" "$C_RESET" "$C_BOLD$C_GREEN" "$C_RESET"
  printf '      %s(copy that line and press Enter in your terminal)%s\n\n' "$C_DIM" "$C_RESET"

  if [ "$MATCHBOX_READY" != 1 ]; then
    printf '  %sSign in:%s %sfornace-matchbox login%s\n\n' "$C_INK" "$C_RESET" "$C_BOLD$C_GREEN" "$C_RESET"
  fi

  printf '  %s2.%s Start working.                 %spi%s\n' "$C_GREEN" "$C_RESET" "$C_BOLD$C_GREEN" "$C_RESET"
  printf '      %s(type pi and press Enter)%s\n\n' "$C_DIM" "$C_RESET"

  printf '  %sIf anything looks wrong, run this and it will explain what is missing:%s\n' "$C_INK" "$C_RESET"
  printf '      %ssoffio doctor%s\n\n' "$C_BOLD$C_INK" "$C_RESET"
else
  printf '\n  You are all set.\n\n'
  printf '  Do this next:\n\n'
  printf '    1. Open the cmux terminal:  open -a cmux\n'
  if [ "$MATCHBOX_READY" != 1 ]; then
    printf '       Sign in:               fornace-matchbox login\n'
  fi
  printf '    2. Start working:           pi\n\n'
  printf '  If anything looks wrong, run: soffio doctor\n\n'
fi
