#!/usr/bin/env bash
#
# Plugsky CLI installer
# ---------------------
# Installs the Plugsky CLI — a sovereign AI coding agent.
# Built from the OpenCode fork with 31 Plugsky models.
#
# Usage:
#   curl -fsSL https://plugsky.com/install | bash
#   curl -fsSL https://plugsky.com/install | bash -s -- --api-key sk-live-...
#
set -euo pipefail

PLUGSKY_VERSION="${PLUGSKY_VERSION:-0.1.1}"
PLUGSKY_HOME="${PLUGSKY_HOME:-$HOME/.plugsky}"
PLUGSKY_BIN="$PLUGSKY_HOME/bin"
RELEASES="https://github.com/coinplannet/opencode/releases/download/v${PLUGSKY_VERSION}"

BOLD='\033[1m'
MUTED='\033[0;2m'
CYAN='\033[0;36m'
GREEN='\033[0;32m'
ORANGE='\033[38;5;214m'
RED='\033[0;31m'
NC='\033[0m'

logo() {
  cat <<'EOF'

  ██████╗ ██╗     ██╗   ██╗ ██████╗ ██╗  ██╗██╗   ██╗
  ██╔══██╗██║     ██║   ██║██╔════╝ ██║ ██╔╝╚██╗ ██╔╝
  ██████╔╝██║     ██║   ██║██║  ███╗█████╔╝  ╚████╔╝
  ██╔═══╝ ██║     ██║   ██║██║   ██║██╔═██╗   ╚██╔╝
  ██║     ███████╗╚██████╔╝╚██████╔╝██║  ██╗   ██║
  ╚═╝     ╚══════╝ ╚═════╝  ╚═════╝ ╚═╝  ╚═╝   ╚═╝

              Plugsky CLI — AI coding agent
EOF
}

usage() {
  cat <<EOF
Plugsky CLI installer v$PLUGSKY_VERSION

Usage:
  curl -fsSL https://plugsky.com/install | bash
  curl -fsSL https://plugsky.com/install | bash -s -- [options]

Options:
  -h, --help                       Show this help
  -v, --version <ver>              Install a specific version (default: $PLUGSKY_VERSION)
      --no-modify-path             Don't modify .zshrc / .bashrc
      --api-key <key>              Save your Plugsky API key to ~/.plugsky/.env
      --uninstall                  Remove Plugsky CLI

Examples:
  curl -fsSL https://plugsky.com/install | bash
  curl -fsSL https://plugsky.com/install | bash -s -- --api-key sk-live-abc123
  curl -fsSL https://plugsky.com/install | bash -s -- --no-modify-path
EOF
}

detect_suffix() {
  local os arch
  os=$(uname -s)
  case "$os" in
    Darwin*) os="darwin" ;;
    Linux*) os="linux" ;;
    MINGW*|MSYS*|CYGWIN*) os="windows" ;;
    *) echo -e "${RED}Error: unsupported OS: $os${NC}" >&2; exit 1 ;;
  esac

  arch=$(uname -m)
  case "$arch" in
    aarch64|arm64) arch="arm64" ;;
    x86_64) arch="x64" ;;
    *) echo -e "${RED}Error: unsupported architecture: $arch${NC}" >&2; exit 1 ;;
  esac

  if [ "$os" = "darwin" ] && [ "$arch" = "x64" ]; then
    local rosetta
    rosetta=$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)
    [ "$rosetta" = "1" ] && arch="arm64"
  fi

  if [ "$os" = "darwin" ] && [ "$arch" = "x64" ]; then
    echo "$os-x64-baseline"
  else
    echo "$os-$arch"
  fi
}

install_binary() {
  local suffix="$1"
  local url="$RELEASES/opencode-${suffix}.zip"
  local tmpdir
  tmpdir=$(mktemp -d)
  trap "rm -rf '$tmpdir'" RETURN

  echo -e "${MUTED}Downloading Plugsky CLI for ${suffix}…${NC}"
  if ! curl -fsSL --retry 3 -o "$tmpdir/plugsky.zip" "$url"; then
    echo -e "${RED}Error: download failed from $url${NC}" >&2
    exit 1
  fi

  cd "$tmpdir"
  if ! unzip -q plugsky.zip; then
    echo -e "${RED}Error: unzip failed${NC}" >&2
    exit 1
  fi

  if [ ! -f "bin/plugsky" ] && [ ! -f "bin/plugsky.exe" ]; then
    echo -e "${RED}Error: binary not found in zip${NC}" >&2
    exit 1
  fi

  mkdir -p "$PLUGSKY_BIN"
  local binary="bin/plugsky"
  [ ! -f "$binary" ] && binary="bin/plugsky.exe"
  cp "$binary" "$PLUGSKY_BIN/plugsky"
  chmod +x "$PLUGSKY_BIN/plugsky"
  echo -e "${GREEN}  ✓ Installed to $PLUGSKY_BIN/plugsky${NC}"
}

write_config() {
  local api_key="${1:-}"
  mkdir -p "$PLUGSKY_HOME"

  cat > "$PLUGSKY_HOME/config.json" <<EOF
{
  "\$schema": "https://plugsky.com/schema/config.json",
  "theme": "plugsky",
  "provider": {
    "plugsky": {
      "name": "Plugsky",
      "options": {
        "baseURL": "https://api.plugsky.com/v1",
        "apiKey": "\${PLUGSKY_API_KEY}"
      },
      "models": {
        "plugsky-pro":        { "name": "Plugsky Pro" },
        "plugsky-max":        { "name": "Plugsky Max" },
        "plugsky-frontier":   { "name": "Plugsky Frontier" },
        "plugsky-fast":       { "name": "Plugsky Fast" },
        "plugsky-micro":      { "name": "Plugsky Micro" },
        "plugsky-reasoning":  { "name": "Plugsky Reasoning" },
        "plugsky-longctx":    { "name": "Plugsky Long Context" }
      }
    }
  },
  "model": "plugsky-pro",
  "small_model": "plugsky-micro"
}
EOF
  echo -e "${GREEN}  ✓ Wrote $PLUGSKY_HOME/config.json${NC}"

  if [ -n "$api_key" ]; then
    cat > "$PLUGSKY_HOME/.env" <<EOF
PLUGSKY_API_KEY=$api_key
EOF
    chmod 600 "$PLUGSKY_HOME/.env"
    echo -e "${GREEN}  ✓ Saved API key to $PLUGSKY_HOME/.env${NC}"
  fi
}

write_welcome() {
  cat > "$PLUGSKY_HOME/WELCOME.txt" <<'WELCOME'
╔══════════════════════════════════════════════════════════════════╗
║                      Welcome to Plugsky CLI                     ║
║         AI coding agent — powered by plugsky-pro                ║
╚══════════════════════════════════════════════════════════════════╝

  Quick start:

    1. Set your API key (one time):
         export PLUGSKY_API_KEY=sk-live-...

    2. Run the agent:
         plugsky

    3. Switch models (inside the agent):
         /model plugsky-max
         /model plugsky-frontier
         /model plugsky-fast

  Docs:    https://plugsky.com/docs
  Status:  https://plugsky.com/status
  Get key: https://plugsky.com/dashboard
WELCOME
  echo -e "${GREEN}  ✓ Wrote $PLUGSKY_HOME/WELCOME.txt${NC}"
}

add_to_path() {
  local rc_file="$1"
  local line='export PATH="$HOME/.plugsky/bin:$PATH"'
  if [ -f "$rc_file" ] && grep -qF '.plugsky/bin' "$rc_file"; then
    return 0
  fi
  if [ -f "$rc_file" ]; then
    printf '\n# Plugsky CLI\n%s\n' "$line" >> "$rc_file"
  else
    printf '%s\n' "$line" > "$rc_file"
  fi
  echo -e "${GREEN}  ✓ Added ~/.plugsky/bin to PATH in $rc_file${NC}"
}

install() {
  echo
  logo
  echo
  echo -e "${BOLD}Installing Plugsky CLI v${PLUGSKY_VERSION}${NC}"
  echo

  local suffix
  suffix=$(detect_suffix)
  echo -e "${MUTED}Detected: $suffix${NC}"

  install_binary "$suffix"
  write_config "${PLUGSKY_API_KEY:-}"
  write_welcome

  if [ "${NO_MODIFY_PATH:-false}" = "true" ]; then
    echo -e "${MUTED}Skipped modifying shell rc (--no-modify-path)${NC}"
  else
    local os
    os=$(uname -s)
    case "$os" in
      Darwin*|Linux*)
        [ -f "$HOME/.zshrc" ] && add_to_path "$HOME/.zshrc"
        [ -f "$HOME/.bashrc" ] && add_to_path "$HOME/.bashrc"
        ;;
    esac
  fi

  echo
  echo -e "${BOLD}Verifying…${NC}"
  version_output=$("$PLUGSKY_BIN/plugsky" --version 2>&1 | head -3 || true)
  if [ -n "$version_output" ]; then
    echo -e "${GREEN}  ✓ $version_output${NC}"
  else
    echo -e "${ORANGE}  ! Binary installed. Run 'plugsky --version' to confirm.${NC}"
  fi

  echo
  echo -e "${BOLD}${GREEN}Plugsky CLI v${PLUGSKY_VERSION} installed!${NC}"
  echo
  echo -e "  ${CYAN}Next steps:${NC}"
  echo -e "    1. ${BOLD}Restart your terminal${NC} (or: ${MUTED}source ~/.zshrc${NC})"
  echo -e "    2. Get a key: ${CYAN}https://plugsky.com/dashboard${NC}"
  echo -e "    3. Set it:    ${MUTED}export PLUGSKY_API_KEY=sk-live-…${NC}"
  echo -e "    4. Run:       ${MUTED}plugsky${NC}"
  echo
}

uninstall() {
  echo -e "${ORANGE}Removing $PLUGSKY_HOME …${NC}"
  rm -rf "$PLUGSKY_HOME"
  for rc in "$HOME/.zshrc" "$HOME/.bashrc"; do
    if [ -f "$rc" ]; then
      sed -i.bak '/\.plugsky\/bin/d' "$rc" 2>/dev/null || true
    fi
  done
  echo -e "${GREEN}  ✓ Removed. Restart your terminal.${NC}"
}

NO_MODIFY_PATH=false
PLUGSKY_API_KEY=""
ACTION="install"

while [[ $# -gt 0 ]]; do
  case "$1" in
    -h|--help) usage; exit 0 ;;
    -v|--version) PLUGSKY_VERSION="$2"; shift 2 ;;
    --no-modify-path) NO_MODIFY_PATH=true; shift ;;
    --api-key) PLUGSKY_API_KEY="$2"; shift 2 ;;
    --uninstall) ACTION="uninstall"; shift ;;
    --) shift ;;
    *) echo -e "${ORANGE}Warning: unknown option '$1'${NC}" >&2; shift ;;
  esac
done

case "$ACTION" in
  install) install ;;
  uninstall) uninstall ;;
esac
