#!/bin/bash
set -e

# BillingNow CLI Installer
# Usage: curl -fsSL https://billingnow.com/cli/install.sh | bash

VERSION="${BN_VERSION:-latest}"
INSTALL_DIR="${BN_INSTALL_DIR:-$HOME/.billingnow}"
BIN_DIR="${BN_BIN_DIR:-$HOME/.local/bin}"

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

info() { echo -e "${GREEN}✓${NC} $1"; }
warn() { echo -e "${YELLOW}!${NC} $1"; }
error() { echo -e "${RED}✗${NC} $1"; exit 1; }

# Check for Node.js
check_node() {
  if ! command -v node &> /dev/null; then
    error "Node.js is required but not installed. Please install Node.js 18+ first."
  fi

  NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
  if [ "$NODE_VERSION" -lt 18 ]; then
    error "Node.js 18+ is required. Current version: $(node -v)"
  fi
}

main() {
  echo ""
  echo -e "${BLUE}╔══════════════════════════════════════╗${NC}"
  echo -e "${BLUE}║     BillingNow CLI Installer         ║${NC}"
  echo -e "${BLUE}╚══════════════════════════════════════╝${NC}"
  echo ""

  check_node

  # Create directories
  mkdir -p "$INSTALL_DIR"
  mkdir -p "$BIN_DIR"

  # Download URL
  BASE_URL="${BN_BASE_URL:-https://billingnow.com/cli}"
  DOWNLOAD_URL="${BASE_URL}/bn-${VERSION}.tar.gz"

  info "Downloading BillingNow CLI..."

  TEMP_DIR=$(mktemp -d)
  TEMP_FILE="$TEMP_DIR/bn.tar.gz"

  if command -v curl &> /dev/null; then
    curl -fsSL "$DOWNLOAD_URL" -o "$TEMP_FILE" || error "Download failed"
  elif command -v wget &> /dev/null; then
    wget -q "$DOWNLOAD_URL" -O "$TEMP_FILE" || error "Download failed"
  else
    error "Neither curl nor wget found. Please install one of them."
  fi

  info "Installing to $INSTALL_DIR..."
  tar -xzf "$TEMP_FILE" -C "$INSTALL_DIR"
  rm -rf "$TEMP_DIR"

  # Move files to expected locations
  # Tarball contains: dist/bin/bn.js and skills/
  if [ -d "$INSTALL_DIR/dist/bin" ]; then
    rm -rf "$INSTALL_DIR/bin" 2>/dev/null || true
    mv "$INSTALL_DIR/dist/bin" "$INSTALL_DIR/bin"
    rmdir "$INSTALL_DIR/dist" 2>/dev/null || true
  fi

  # Create package.json for ESM support
  echo '{"type":"module"}' > "$INSTALL_DIR/bin/package.json"

  # Create wrapper script
  cat > "$BIN_DIR/bn" << 'EOF'
#!/bin/bash
exec node "$HOME/.billingnow/bin/bn.js" "$@"
EOF
  chmod +x "$BIN_DIR/bn"

  # Check if BIN_DIR is in PATH
  if [[ ":$PATH:" != *":$BIN_DIR:"* ]]; then
    echo ""
    warn "$BIN_DIR is not in your PATH"
    echo ""
    echo "  Add this to your shell profile (~/.bashrc, ~/.zshrc, etc.):"
    echo ""
    echo -e "    ${BLUE}export PATH=\"\$HOME/.local/bin:\$PATH\"${NC}"
    echo ""
    echo "  Then restart your terminal or run:"
    echo ""
    echo -e "    ${BLUE}source ~/.bashrc${NC}  # or ~/.zshrc"
    echo ""
  fi

  echo ""
  info "BillingNow CLI installed successfully!"
  echo ""
  echo "  Get started:"
  echo -e "    ${BLUE}bn --help${NC}      Show all commands"
  echo -e "    ${BLUE}bn login${NC}       Authenticate with BillingNow"
  echo ""
}

main "$@"
