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

SITE="https://fluidstate.ai"
BINARY="fluidstate"
VERSION="${FLUIDSTATE_VERSION:-latest}"
TMP_DIR=""

# Colors
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; NC='\033[0m'

info()    { printf "${BLUE}info${NC}  %s\n" "$*"; }
success() { printf "${GREEN}done${NC}  %s\n" "$*"; }
warn()    { printf "${YELLOW}warn${NC}  %s\n" "$*"; }
error()   { printf "${RED}error${NC} %s\n" "$*" >&2; exit 1; }

# Detect OS + arch → Rust target triple
detect_target() {
  local os arch
  os=$(uname -s)
  arch=$(uname -m)

  case "$os" in
    Darwin)
      case "$arch" in
        arm64)  echo "aarch64-apple-darwin" ;;
        x86_64) echo "x86_64-apple-darwin" ;;
        *)      error "Unsupported macOS arch: $arch" ;;
      esac
      ;;
    Linux)
      case "$arch" in
        x86_64)  echo "x86_64-unknown-linux-gnu" ;;
        aarch64) echo "aarch64-unknown-linux-gnu" ;;
        *)       error "Unsupported Linux arch: $arch" ;;
      esac
      ;;
    *)
      error "Unsupported OS: $os. On Windows use WSL2."
      ;;
  esac
}

# Resolve install dir — prefer /usr/local/bin, fall back to ~/.local/bin
resolve_install_dir() {
  if [ -w "/usr/local/bin" ] 2>/dev/null || sudo -n true 2>/dev/null; then
    echo "/usr/local/bin"
  else
    local dir="$HOME/.local/bin"
    mkdir -p "$dir"
    echo "$dir"
  fi
}

# Check that the install dir is on PATH
check_path() {
  local dir="$1"
  if [[ ":$PATH:" != *":$dir:"* ]]; then
    warn "$dir is not in your PATH."
    warn "Add this to your shell profile:"
    warn "  export PATH=\"$dir:\$PATH\""
  fi
}

main() {
  printf "\n  Installing ${BINARY}...\n\n"

  local target install_dir download_url tag

  target=$(detect_target)
  install_dir=$(resolve_install_dir)

  # Resolve version tag
  if [ "$VERSION" = "latest" ]; then
    info "Fetching latest release..."
    tag=$(curl -fsSL "${SITE}/api/releases/latest" \
      | grep '"tag_name"' | head -1 | sed 's/.*"tag_name": *"\([^"]*\)".*/\1/')
    [ -z "$tag" ] && error "Could not determine latest release."
  else
    tag="$VERSION"
  fi

  info "Version: $tag"
  info "Target:  $target"
  info "Install: $install_dir"
  printf "\n"

  download_url="${SITE}/api/releases/download/${tag}/${BINARY}-${target}.tar.gz"

  TMP_DIR=$(mktemp -d)
  trap 'rm -rf "$TMP_DIR"' EXIT

  info "Downloading..."
  if ! curl -fsSL --progress-bar "$download_url" | tar xz -C "$TMP_DIR"; then
    error "Download failed. Release may not have a binary for $target yet.\nURL: $download_url"
  fi

  local bin_path="$TMP_DIR/$BINARY"
  [ ! -f "$bin_path" ] && error "Binary not found in archive."
  chmod +x "$bin_path"

  # Install (with sudo if needed)
  if [ -w "$install_dir" ]; then
    mv "$bin_path" "$install_dir/$BINARY"
  else
    info "Requesting sudo to install to $install_dir..."
    sudo mv "$bin_path" "$install_dir/$BINARY"
  fi

  success "Installed $BINARY $tag → $install_dir/$BINARY"
  check_path "$install_dir"

  printf "\n  Run ${GREEN}fluidstate${NC} in any project directory.\n\n"
}

main "$@"
