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

REPO="https://github.com/DekaPrayoga/AurixAgent.git"
INSTALL_DIR="$HOME/.aurix/agent"
BIN_DIR="$HOME/.local/bin"

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

banner() {
  echo -e "${CYAN}"
  echo ' █████╗ ██╗   ██╗██████╗ ██╗██╗  ██╗'
  echo '██╔══██╗██║   ██║██╔══██╗██║╚██╗██╔╝'
  echo '███████║██║   ██║██████╔╝██║ ╚███╔╝'
  echo '██╔══██║██║   ██║██╔══██╗██║ ██╔██╗'
  echo '██║  ██║╚██████╔╝██║  ██║██║██╔╝ ██╗'
  echo '╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═╝╚═╝╚═╝  ╚═╝'
  echo -e "${NC}"
  echo -e "${BOLD}AURIX Agent Installer${NC}"
  echo ""
}

info()  { echo -e "${GREEN}[✓]${NC} $1"; }
warn()  { echo -e "${CYAN}[!]${NC} $1"; }
fail()  { echo -e "${RED}[✗]${NC} $1"; exit 1; }

check_runtime() {
  if command -v bun &>/dev/null; then
    RUNTIME="bun"
    info "Found Bun $(bun --version)"
  elif command -v node &>/dev/null; then
    RUNTIME="node"
    local ver
    ver=$(node --version | sed 's/v//')
    local major=${ver%%.*}
    if [ "$major" -lt 22 ]; then
      fail "Node.js 22+ required (found $ver). Install Bun: curl -fsSL https://bun.sh/install | bash"
    fi
    info "Found Node.js $ver"
  else
    warn "No runtime found. Installing Bun..."
    curl -fsSL https://bun.sh/install | bash
    export BUN_INSTALL="$HOME/.bun"
    export PATH="$BUN_INSTALL/bin:$PATH"
    RUNTIME="bun"
    info "Bun installed $(bun --version)"
  fi
}

install_deps() {
  command -v git &>/dev/null || fail "git is required. Install: apt install git"
  command -v curl &>/dev/null || fail "curl is required."
}

clone_or_update() {
  if [ -d "$INSTALL_DIR/.git" ]; then
    info "Updating existing installation..."
    cd "$INSTALL_DIR"
    git pull --ff-only origin main
  else
    info "Cloning AURIX Agent..."
    mkdir -p "$(dirname "$INSTALL_DIR")"
    git clone "$REPO" "$INSTALL_DIR"
    cd "$INSTALL_DIR"
  fi
}

build() {
  info "Installing dependencies..."
  if [ "$RUNTIME" = "bun" ]; then
    bun install
    info "Building..."
    bun run build
  else
    npm install
    info "Building..."
    npx tsc -p tsconfig.json
  fi
}

link_binary() {
  mkdir -p "$BIN_DIR"

  cat > "$BIN_DIR/aurix" << 'WRAPPER'
#!/usr/bin/env bash
INSTALL_DIR="$HOME/.aurix/agent"
if [ ! -d "$INSTALL_DIR" ]; then
  echo "AURIX not installed. Run: curl -fsSL https://api.haikz.me/install.sh | bash"
  exit 1
fi
cd "$INSTALL_DIR"
if command -v bun &>/dev/null; then
  exec bun run dist/index.js "$@"
else
  exec node dist/index.js "$@"
fi
WRAPPER

  chmod +x "$BIN_DIR/aurix"

  if [[ ":$PATH:" != *":$BIN_DIR:"* ]]; then
    local shell_rc=""
    if [ -n "${ZSH_VERSION:-}" ]; then
      shell_rc="$HOME/.zshrc"
    elif [ -n "${BASH_VERSION:-}" ]; then
      shell_rc="$HOME/.bashrc"
    fi

    if [ -n "$shell_rc" ]; then
      echo "export PATH=\"$BIN_DIR:\$PATH\"" >> "$shell_rc"
      export PATH="$BIN_DIR:$PATH"
      warn "Added $BIN_DIR to PATH in $shell_rc"
    fi
  fi

  info "Installed aurix command to $BIN_DIR/aurix"
}

finish() {
  echo ""
  echo -e "${GREEN}${BOLD}AURIX Agent installed successfully!${NC}"
  echo ""
  echo -e "  ${CYAN}aurix${NC}           Start interactive session"
  echo -e "  ${CYAN}aurix setup${NC}     Configure provider & API key"
  echo -e "  ${CYAN}aurix gateway${NC}   Start Discord/Telegram/WhatsApp bots"
  echo -e "  ${CYAN}aurix --help${NC}    Show all options"
  echo ""
  echo -e "Run ${BOLD}aurix setup${NC} to get started."
}

main() {
  banner
  install_deps
  check_runtime
  clone_or_update
  build
  link_binary
  finish
}

main "$@"
