#!/usr/bin/env bash
set -euo pipefail

CYAN='\033[0;36m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
RED='\033[0;31m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'

print_step() { echo -e "${BLUE}▸${NC} $1"; }
print_ok() { echo -e "${GREEN}✓${NC} $1"; }
print_warn() { echo -e "${YELLOW}!${NC} $1"; }
print_err() { echo -e "${RED}✗${NC} $1"; }

# Config (can override via env)
DOWNLOAD_BASE="${DOWNLOAD_BASE:-https://static.cloudbase.net/cli}"
CHANNEL="${CHANNEL:-stable}" # stable | beta
VERSION="${VERSION:-latest}"

# Detect OS/ARCH
print_step "Detecting system architecture..."
OS_RAW="$(uname -s)"
case "$OS_RAW" in
  Linux*) OS=linux ;;
  Darwin*) OS=darwin ;;
  *) print_err "Unsupported OS: $OS_RAW"; exit 1 ;;
esac
ARCH_RAW="$(uname -m)"
case "$ARCH_RAW" in
  x86_64|amd64) ARCH=x64 ;;
  arm64|aarch64) ARCH=arm64 ;;
  *) print_err "Unsupported ARCH: $ARCH_RAW"; exit 1 ;;
esac
print_ok "Detected ${OS}/${ARCH}"

# Paths
ROOT_DIR="$HOME/.local/share/cloudbase-cli"
VERSIONS_DIR="$ROOT_DIR/versions"
BIN_DIR="$HOME/.local/bin"
CURRENT_LINK="$ROOT_DIR/current"
TMP_DIR="$VERSIONS_DIR/.tmp-${VERSION}-$(date +%s)"

cleanup() { rm -rf "$TMP_DIR" 2>/dev/null || true; }
trap cleanup EXIT

print_step "Preparing directories..."
mkdir -p "$TMP_DIR" "$BIN_DIR" "$VERSIONS_DIR"
print_ok "Directories ready"

# Resolve version when latest
if [[ "$VERSION" == "latest" || -z "$VERSION" ]]; then
  print_step "Resolving latest version (channel=$CHANNEL)..."
  VER_URL="${DOWNLOAD_BASE}/${CHANNEL}.txt"
  echo -e "${DIM}${VER_URL}${NC}"
  curl -fL --retry 3 --retry-delay 1 -o "$TMP_DIR/version.txt" "$VER_URL"
  VERSION="$(tr -d ' \r\n\t' < "$TMP_DIR/version.txt")"
  if [[ -z "$VERSION" ]]; then
    print_err "Failed to resolve version from ${VER_URL}"; exit 1
  fi
  print_ok "Resolved version: ${VERSION}"
fi

TARBALL_NAME="cloudbase-cli-${VERSION}.tar.gz"
PACKAGE_URL="${DOWNLOAD_BASE}/${VERSION}/${OS}/${ARCH}/${TARBALL_NAME}"
CHECKSUM_URL="${PACKAGE_URL}.sha256"

print_step "Downloading package..."
echo -e "${DIM}${PACKAGE_URL}${NC}"
curl -fL --retry 3 --retry-delay 1 -o "$TMP_DIR/$TARBALL_NAME" "$PACKAGE_URL"
print_ok "Package downloaded"

print_step "Downloading checksum..."
echo -e "${DIM}${CHECKSUM_URL}${NC}"
curl -fL --retry 3 --retry-delay 1 -o "$TMP_DIR/$TARBALL_NAME.sha256" "$CHECKSUM_URL"
print_ok "Checksum downloaded"

print_step "Verifying checksum..."
if command -v shasum >/dev/null 2>&1; then
  CALC_SUM="$(shasum -a 256 "$TMP_DIR/$TARBALL_NAME" | awk '{print $1}')"
else
  CALC_SUM="$(sha256sum "$TMP_DIR/$TARBALL_NAME" | awk '{print $1}')"
fi
FILE_SUM="$(awk '{print $1}' "$TMP_DIR/$TARBALL_NAME.sha256")"
if [[ "$CALC_SUM" != "$FILE_SUM" || -z "$FILE_SUM" ]]; then
  print_err "Checksum mismatch"; echo "expected: $FILE_SUM"; echo "actual:   $CALC_SUM"; exit 1
fi
print_ok "Checksum OK"

print_step "Extracting..."
EXTRACT_DIR="$TMP_DIR/extract"
mkdir -p "$EXTRACT_DIR"
# Archive contains top-level cloudbase-cli-<version>/, strip it
tar -xzf "$TMP_DIR/$TARBALL_NAME" -C "$EXTRACT_DIR" --strip-components=1
print_ok "Extracted"

print_step "Installing version ${VERSION}..."
TARGET_DIR="$VERSIONS_DIR/$VERSION"
if [[ -e "$TARGET_DIR" ]]; then
  print_warn "Target exists, replacing: $TARGET_DIR"
  rm -rf "$TARGET_DIR"
fi
mv "$EXTRACT_DIR" "$TARGET_DIR"
print_ok "Installed to $TARGET_DIR"

print_step "Linking executables..."
# Maintain current symlink for diagnostics and atomic switch
ln -sfn "$TARGET_DIR" "$CURRENT_LINK"

# Point user-facing links to current/bin/*
ln -sfn "$CURRENT_LINK/bin/cloudbase" "$BIN_DIR/cloudbase"
ln -sfn "$CURRENT_LINK/bin/tcb" "$BIN_DIR/tcb"
ln -sfn "$CURRENT_LINK/bin/cloudbase-mcp" "$BIN_DIR/cloudbase-mcp"
print_ok "Symlinks updated in $BIN_DIR"

# PATH instruction
if ! echo ":$PATH:" | grep -q ":$BIN_DIR:"; then
  echo -e "${BOLD}Next Steps${NC}"
  echo -e "1. Add ~/.local/bin to PATH if not present:"
  SHELL_NAME="$(basename "${SHELL:-}")"
  case "$SHELL_NAME" in
    bash) echo -e "  echo 'export PATH=\"$HOME/.local/bin:$PATH\"' >> ~/.bashrc && source ~/.bashrc" ;;
    zsh)  echo -e "  echo 'export PATH=\"$HOME/.local/bin:$PATH\"' >> ~/.zshrc && source ~/.zshrc" ;;
    fish) echo -e "  mkdir -p $HOME/.config/fish; echo 'fish_add_path $HOME/.local/bin' >> $HOME/.config/fish/config.fish && source $HOME/.config/fish/config.fish" ;;
    *)    echo -e "  export PATH=\"$HOME/.local/bin:$PATH\"" ;;
  esac
fi

print_ok "CloudBase CLI ${VERSION} installed"
which cloudbase >/dev/null 2>&1 && echo -e "Using: $(command -v cloudbase)"
