#!/usr/bin/env sh
# qorin-agent installer — runs on macOS and Linux.
#
# Usage:
#   curl -fsSL https://dl.qorin.dev/install.sh | sh
#
# What it does:
#   1. Detects OS + arch (darwin/linux × amd64/arm64).
#   2. Downloads the matching binary from https://dl.qorin.dev/.
#   3. Installs it in ~/.local/bin/qorin-agent and chmod +x.
#   4. Verifies the binary runs (`qorin-agent --version`).
#   5. If ~/.local/bin is not in PATH, offers to add it to the user's
#      shell rc (zsh/bash/fish), explaining why.
#   6. Prints next-step hint: `qorin-agent login`.
#
# The script is POSIX sh — runs on the bare /bin/sh of macOS and Linux.
# Interactive prompts read from /dev/tty so they work even when this
# script is piped from curl (stdin is busy with the script body itself).

set -eu

DOWNLOAD_BASE="${QORIN_DOWNLOAD_BASE:-https://dl.qorin.dev}"
INSTALL_DIR="${QORIN_INSTALL_DIR:-$HOME/.local/bin}"
BINARY_NAME="qorin-agent"

# ─── Pretty printers ──────────────────────────────────────────────────────────
# Disable colors when stdout isn't a TTY (e.g. piping to a file).
if [ -t 1 ]; then
  c_bold=$(printf '\033[1m')
  c_dim=$(printf '\033[2m')
  c_red=$(printf '\033[31m')
  c_grn=$(printf '\033[32m')
  c_ylw=$(printf '\033[33m')
  c_rst=$(printf '\033[0m')
else
  c_bold=""; c_dim=""; c_red=""; c_grn=""; c_ylw=""; c_rst=""
fi

info() { printf '%s→%s %s\n' "$c_bold" "$c_rst" "$1"; }
ok()   { printf '%s✓%s %s\n' "$c_grn" "$c_rst" "$1"; }
warn() { printf '%s⚠%s %s\n' "$c_ylw" "$c_rst" "$1" >&2; }
err()  { printf '%s✗%s %s\n' "$c_red" "$c_rst" "$1" >&2; }
die()  { err "$1"; exit 1; }

# ─── 1. Detect platform ───────────────────────────────────────────────────────
detect_os() {
  uname_s=$(uname -s)
  case "$uname_s" in
    Darwin) printf "darwin" ;;
    Linux)  printf "linux"  ;;
    *) die "Unsupported OS: $uname_s. qorin-agent only supports macOS and Linux." ;;
  esac
}

detect_arch() {
  uname_m=$(uname -m)
  case "$uname_m" in
    x86_64|amd64)  printf "amd64" ;;
    arm64|aarch64) printf "arm64" ;;
    *) die "Unsupported architecture: $uname_m." ;;
  esac
}

OS=$(detect_os)
ARCH=$(detect_arch)
PLATFORM="${OS}-${ARCH}"
BINARY_URL="${DOWNLOAD_BASE}/${BINARY_NAME}-${PLATFORM}"

info "Detected platform: ${c_bold}${PLATFORM}${c_rst}"

# ─── 2. Download ──────────────────────────────────────────────────────────────
mkdir -p "$INSTALL_DIR"
INSTALL_PATH="${INSTALL_DIR}/${BINARY_NAME}"

# If a previous install exists, back it up so we can restore on failure.
backup=""
if [ -e "$INSTALL_PATH" ]; then
  backup="${INSTALL_PATH}.bak.$$"
  mv "$INSTALL_PATH" "$backup"
fi

info "Downloading from $BINARY_URL"
if ! curl -fL --progress-bar "$BINARY_URL" -o "$INSTALL_PATH"; then
  if [ -n "$backup" ]; then mv "$backup" "$INSTALL_PATH"; fi
  die "Download failed. Check your internet connection and try again."
fi

chmod +x "$INSTALL_PATH"

# ─── 3. Verify ────────────────────────────────────────────────────────────────
if ! "$INSTALL_PATH" --version >/dev/null 2>&1; then
  if [ -n "$backup" ]; then mv "$backup" "$INSTALL_PATH"; fi
  die "Binary downloaded but doesn't run. Quarantine on macOS? Try: xattr -dr com.apple.quarantine $INSTALL_PATH"
fi
[ -n "$backup" ] && rm -f "$backup"

ok "Installed to $INSTALL_PATH"

# ─── 3.5. Runtime dependencies check ──────────────────────────────────────────
# qorin-agent shells out to `git` for repository operations. The CLI
# session manager is now Go-native (PTY) so tmux is no longer required.
# We don't bundle git — the user installs whichever version they want.
# This step just *checks* and prints the right install command for the
# detected platform if anything's missing.
missing=""
for dep in git; do
  if ! command -v "$dep" >/dev/null 2>&1; then
    missing="$missing $dep"
  fi
done
if [ -n "$missing" ]; then
  printf "\n"
  warn "Missing runtime dependencies:$missing"
  case "$OS" in
    darwin)
      printf "  Install with Homebrew:\n"
      printf "      %sbrew install%s%s\n\n" "$c_bold" "$c_rst" "$missing"
      ;;
    linux)
      if command -v apt-get >/dev/null 2>&1; then
        printf "  Install with apt:\n"
        printf "      %ssudo apt-get install -y%s%s\n\n" "$c_bold" "$c_rst" "$missing"
      elif command -v dnf >/dev/null 2>&1; then
        printf "  Install with dnf:\n"
        printf "      %ssudo dnf install -y%s%s\n\n" "$c_bold" "$c_rst" "$missing"
      elif command -v pacman >/dev/null 2>&1; then
        printf "  Install with pacman:\n"
        printf "      %ssudo pacman -S%s%s\n\n" "$c_bold" "$c_rst" "$missing"
      else
        printf "  Use your package manager to install:%s\n\n" "$missing"
      fi
      ;;
  esac
  printf "  qorin-agent will fail at repository registration without git.\n\n"
fi

# ─── 4. PATH check ────────────────────────────────────────────────────────────
# Is INSTALL_DIR already in PATH?
case ":$PATH:" in
  *":$INSTALL_DIR:"*)
    PATH_OK=1
    ;;
  *)
    PATH_OK=0
    ;;
esac

if [ "$PATH_OK" = "1" ]; then
  ok "$INSTALL_DIR is already in your PATH."
else
  printf "\n"
  printf "%s$INSTALL_DIR is not in your PATH.%s\n" "$c_ylw" "$c_rst"
  printf "Right now you'd have to run %s$INSTALL_PATH%s every time. Adding\n" "$c_bold" "$c_rst"
  printf "the directory to your PATH lets you just type %sqorin-agent%s.\n\n" "$c_bold" "$c_rst"

  # Detect the user's shell and the right rc file to update.
  shell_name=$(basename "${SHELL:-/bin/sh}")
  case "$shell_name" in
    zsh)  RC_FILE="$HOME/.zshrc"; EXPORT_LINE='export PATH="$HOME/.local/bin:$PATH"' ;;
    bash) RC_FILE="$HOME/.bashrc"; EXPORT_LINE='export PATH="$HOME/.local/bin:$PATH"' ;;
    fish) RC_FILE="$HOME/.config/fish/config.fish"; EXPORT_LINE='set -gx PATH $HOME/.local/bin $PATH' ;;
    *)    RC_FILE=""; EXPORT_LINE='export PATH="$HOME/.local/bin:$PATH"' ;;
  esac

  if [ -n "$RC_FILE" ] && [ -t 0 -o -e /dev/tty ]; then
    printf "Add %s to %s%s%s? %s[Y/n]%s " \
      "this line" "$c_bold" "$RC_FILE" "$c_rst" "$c_dim" "$c_rst"
    # Read from /dev/tty to bypass the curl|sh stdin pipe.
    read response < /dev/tty || response="n"
    case "$response" in
      ""|y|Y|yes|YES)
        mkdir -p "$(dirname "$RC_FILE")"
        # Idempotent: only add if not already there.
        if [ -f "$RC_FILE" ] && grep -Fq "$EXPORT_LINE" "$RC_FILE"; then
          ok "Already present in $RC_FILE."
        else
          {
            printf '\n# Added by qorin-agent installer (https://dl.qorin.dev)\n'
            printf '%s\n' "$EXPORT_LINE"
          } >> "$RC_FILE"
          ok "Added to $RC_FILE. Open a new terminal or run: source $RC_FILE"
        fi
        ;;
      *)
        warn "Skipped. Add this manually to your shell rc when you're ready:"
        printf "    %s\n" "$EXPORT_LINE"
        ;;
    esac
  else
    warn "Add this to your shell startup file when you're ready:"
    printf "    %s\n" "$EXPORT_LINE"
  fi
fi

# ─── 5. Next steps ────────────────────────────────────────────────────────────
printf "\n"
ok "qorin-agent installed."
printf "\n"
printf "Next steps:\n"
printf "  %sqorin-agent login%s    Authorize this machine in your browser\n" "$c_bold" "$c_rst"
printf "  %sqorin-agent serve%s    Start the agent (foreground; for daemon mode see docs)\n" "$c_bold" "$c_rst"
printf "\n"
