#!/usr/bin/env sh
# ─────────────────────────────────────────────────────────────────────────────
# A1 Installer — Know Your Agent
# Usage:  curl -fsSL https://get.a1.dev/install.sh | sh
#   or:   curl -fsSL https://github.com/dyologician/a1/releases/latest/download/install.sh | sh
#
# What this does:
#   1. Downloads the right A1 binary for your system
#   2. Puts it in ~/.a1/bin
#   3. Creates an `a1` command you can run anywhere
#   4. Adds `a1` to your PATH
#   5. Prints "Run: a1 start" when done
#
# Supports: macOS (Apple Silicon + Intel), Linux (x86_64 + ARM64)
# ─────────────────────────────────────────────────────────────────────────────

set -e

VERSION="2.8.0"
A1_HOME="${A1_HOME:-$HOME/.a1}"
BIN_DIR="$A1_HOME/bin"
GW_BIN="$BIN_DIR/a1-gateway"
A1_CMD="$BIN_DIR/a1"
GH_BASE="https://github.com/dyologician/a1/releases/download/v${VERSION}"

GREEN='\033[0;32m'
CYAN='\033[0;36m'
BOLD='\033[1m'
DIM='\033[2m'
RED='\033[0;31m'
RESET='\033[0m'

log()  { printf "  %s\n" "$1"; }
ok()   { printf "  ${GREEN}✓${RESET} %s\n" "$1"; }
info() { printf "  ${DIM}%s${RESET}\n" "$1"; }
fail() { printf "  ${RED}✕ %s${RESET}\n" "$1"; exit 1; }

printf "\n  ${BOLD}🛡️  A1 — Know Your Agent${RESET}  ${DIM}v${VERSION}${RESET}\n\n"

# ── Detect OS + arch ─────────────────────────────────────────────────────────
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)

case "$ARCH" in
  x86_64|amd64)   ARCH="x86_64" ;;
  arm64|aarch64)  ARCH="aarch64" ;;
  *)              fail "Unsupported architecture: $ARCH (supported: x86_64, aarch64)" ;;
esac

case "$OS" in
  darwin) TRIPLE="${ARCH}-apple-darwin" ;;
  linux)  TRIPLE="${ARCH}-unknown-linux-gnu" ;;
  *)      fail "Unsupported OS: $OS (use setup.sh on Windows)" ;;
esac

FILENAME="a1-gateway-${VERSION}-${TRIPLE}"
DL_URL="${GH_BASE}/${FILENAME}"

info "Detected: ${OS}/${ARCH}"

# ── Create directories ────────────────────────────────────────────────────────
mkdir -p "$BIN_DIR"
mkdir -p "$A1_HOME/passports"
mkdir -p "$A1_HOME/logs"

# ── Download binary ───────────────────────────────────────────────────────────
if [ -x "$GW_BIN" ]; then
  CURRENT_VER=$("$GW_BIN" --version 2>/dev/null | grep -o '[0-9]*\.[0-9]*\.[0-9]*' | head -1 || echo "")
  if [ "$CURRENT_VER" = "$VERSION" ]; then
    ok "A1 $VERSION already installed"
    SKIP_DOWNLOAD=1
  fi
fi

if [ -z "${SKIP_DOWNLOAD:-}" ]; then
  log "Downloading A1 $VERSION..."
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL --progress-bar "$DL_URL" -o "$GW_BIN" || fail "Download failed. Check your internet connection."
  elif command -v wget >/dev/null 2>&1; then
    wget -q --show-progress "$DL_URL" -O "$GW_BIN" || fail "Download failed."
  else
    fail "Neither curl nor wget found. Install one and try again."
  fi
  chmod +x "$GW_BIN"
  ok "Downloaded"
fi

# ── Create `a1` wrapper command ───────────────────────────────────────────────
cat > "$A1_CMD" << 'WRAPPER'
#!/usr/bin/env sh
# A1 — Know Your Agent
# Generated by installer — do not edit manually

A1_HOME="${A1_HOME:-$HOME/.a1}"
GW_BIN="$A1_HOME/bin/a1-gateway"
PID_FILE="$A1_HOME/gateway.pid"
LOG_FILE="$A1_HOME/logs/gateway.log"
STUDIO_URL="http://localhost:8080/studio"
HEALTH_URL="http://localhost:8080/healthz"

is_running() { curl -sf "$HEALTH_URL" >/dev/null 2>&1; }

open_browser() {
  if command -v open >/dev/null 2>&1; then open "$STUDIO_URL"
  elif command -v xdg-open >/dev/null 2>&1; then xdg-open "$STUDIO_URL"
  elif command -v wslview >/dev/null 2>&1; then wslview "$STUDIO_URL"
  else echo "  Open: $STUDIO_URL"; fi
}

case "${1:-help}" in

  start)
    if is_running; then
      printf "\n  ✓ A1 is already running\n\n  Studio → %s\n\n" "$STUDIO_URL"
      open_browser; exit 0
    fi
    printf "\n  Starting A1...\n"
    nohup "$GW_BIN" >> "$LOG_FILE" 2>&1 &
    echo $! > "$PID_FILE"
    for i in $(seq 1 30); do
      sleep 1
      if is_running; then
        printf "  ✓ A1 is running\n\n  Studio → \033[1m%s\033[0m\n\n" "$STUDIO_URL"
        open_browser; exit 0
      fi
      printf "."
    done
    printf "\n  ✕ Gateway did not start. Check logs: %s\n" "$LOG_FILE"
    exit 1
    ;;

  stop)
    if [ -f "$PID_FILE" ]; then
      kill "$(cat "$PID_FILE")" 2>/dev/null && printf "  ✓ A1 stopped\n" || true
      rm -f "$PID_FILE"
    else
      printf "  A1 is not running\n"
    fi
    ;;

  restart) "$0" stop; sleep 1; "$0" start ;;

  status)
    if is_running; then printf "  ✓ A1 is running  → %s\n" "$STUDIO_URL"
    else printf "  ✕ A1 is not running  (run: a1 start)\n"; fi
    ;;

  open)
    if is_running; then open_browser
    else printf "  A1 is not running. Run: a1 start\n"; fi
    ;;

  logs)
    tail -f "$LOG_FILE"
    ;;

  update)
    printf "  Updating A1...\n"
    curl -fsSL "https://github.com/dyologician/a1/releases/latest/download/install.sh" | sh
    ;;

  version)
    "$GW_BIN" --version 2>/dev/null || printf "  A1 gateway binary at: %s\n" "$GW_BIN"
    ;;

  help|*)
    printf "\n  \033[1ma1\033[0m — Know Your Agent\n\n"
    printf "  Commands:\n"
    printf "    \033[36ma1 start\033[0m      Start A1 and open Studio in your browser\n"
    printf "    \033[36ma1 stop\033[0m       Stop A1\n"
    printf "    \033[36ma1 restart\033[0m    Restart A1\n"
    printf "    \033[36ma1 status\033[0m     Check if A1 is running\n"
    printf "    \033[36ma1 open\033[0m       Open A1 Studio in your browser\n"
    printf "    \033[36ma1 logs\033[0m       Follow gateway logs (Ctrl+C to stop)\n"
    printf "    \033[36ma1 update\033[0m     Update to the latest version\n"
    printf "    \033[36ma1 version\033[0m    Show installed version\n"
    printf "\n  Studio: %s\n\n" "$STUDIO_URL"
    ;;
esac
WRAPPER

chmod +x "$A1_CMD"
ok "Created 'a1' command"

# ── Add to PATH ───────────────────────────────────────────────────────────────
add_to_path() {
  local shell_rc="$1"
  local export_line="export PATH=\"$BIN_DIR:\$PATH\""
  if [ -f "$shell_rc" ] && grep -q "$BIN_DIR" "$shell_rc" 2>/dev/null; then
    return 0  # Already in PATH
  fi
  printf '\n# A1 — Know Your Agent\n%s\n' "$export_line" >> "$shell_rc"
  ok "Added to PATH in $shell_rc"
}

UPDATED_PATH=0
if [ -f "$HOME/.zshrc" ];   then add_to_path "$HOME/.zshrc";   UPDATED_PATH=1; fi
if [ -f "$HOME/.bashrc" ];  then add_to_path "$HOME/.bashrc";  UPDATED_PATH=1; fi
if [ -f "$HOME/.bash_profile" ] && [ "$UPDATED_PATH" -eq 0 ]; then
  add_to_path "$HOME/.bash_profile"; UPDATED_PATH=1
fi
if [ "$UPDATED_PATH" -eq 0 ]; then
  add_to_path "$HOME/.profile"
fi

# Also export for the current shell session
export PATH="$BIN_DIR:$PATH"

# ── Done ──────────────────────────────────────────────────────────────────────
printf "\n  ${BOLD}${GREEN}✅ A1 installed!${RESET}\n\n"
printf "  ${CYAN}Run this to start A1:${RESET}\n\n"
printf "    ${BOLD}a1 start${RESET}\n\n"
printf "  ${DIM}If 'a1' is not found yet, open a new terminal window first."
printf "\n  Or run now:  %s start${RESET}\n\n" "$A1_CMD"
