#!/bin/bash

# AgentBridge - Quick Install Script
#
# Usage:
#   curl -fsSL https://raw.githubusercontent.com/YOUR_USERNAME/AgentBridge/main/scripts/install.sh | bash
#
# Or:
#   ./scripts/install.sh

set -e

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

log_info() { echo -e "${CYAN}ℹ️  $1${NC}"; }
log_success() { echo -e "${GREEN}✅ $1${NC}"; }
log_warning() { echo -e "${YELLOW}⚠️  $1${NC}"; }
log_error() { echo -e "${RED}❌ $1${NC}"; }

echo ""
echo -e "${CYAN}"
echo "   _                    _   ____       _     _"
echo "  / \\   __ _  ___ _ __ | |_| __ ) _ __(_) __| | __ _  ___"
echo " / _ \\ / _\` |/ _ \\ '_ \\| __|  _ \\| '__| |/ _\` |/ _\` |/ _ \\"
echo "/ ___ \\ (_| |  __/ | | | |_| |_) | |  | | (_| | (_| |  __/"
echo "/_/   \\_\\__, |\\___|_| |_|\\__|____/|_|  |_|\\__,_|\\__, |\\___|"
echo "        |___/                                   |___/"
echo -e "${NC}"
echo "  Bridge AI coding agents to chat platforms"
echo ""

# Check Node.js
if ! command -v node &> /dev/null; then
    log_error "Node.js not found. Please install Node.js 18+ first."
    echo "Visit: https://nodejs.org/"
    exit 1
fi

NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 18 ]; then
    log_error "Node.js 18+ required. Current: $(node -v)"
    exit 1
fi
log_success "Node.js $(node -v)"

# Check Docker
if ! command -v docker &> /dev/null; then
    log_error "Docker not found. Please install Docker first."
    echo "Visit: https://docs.docker.com/get-docker/"
    exit 1
fi
log_success "Docker found"

# Check PM2
if ! command -v pm2 &> /dev/null; then
    log_info "Installing PM2..."
    npm install -g pm2
    log_success "PM2 installed"
else
    log_success "PM2 found"
fi

# Clone or update
INSTALL_DIR="${INSTALL_DIR:-$HOME/AgentBridge}"

if [ -d "$INSTALL_DIR" ]; then
    log_info "Updating existing installation..."
    cd "$INSTALL_DIR"
    git pull origin main
else
    log_info "Cloning repository..."
    git clone https://github.com/YOUR_USERNAME/AgentBridge.git "$INSTALL_DIR"
    cd "$INSTALL_DIR"
fi

# Install dependencies
log_info "Installing dependencies..."
npm install

# Build Docker image
log_info "Building Docker sandbox..."
docker build -t claude-sandbox ./sandbox

# Config check
if [ ! -f "config/config.json" ]; then
    log_warning "Config not found."
    echo ""
    echo "Create config/config.json:"
    echo "  cp config/config.example.json config/config.json"
    echo "  nano config/config.json"
    echo ""
fi

# Link CLI
log_info "Linking CLI..."
npm link

echo ""
log_success "Installation complete!"
echo ""
echo "Next steps:"
echo "  1. Edit config/config.json"
echo "  2. Run: agent-bridge start"
echo ""
echo "Commands:"
echo "  agent-bridge setup   - Interactive setup"
echo "  agent-bridge start   - Start"
echo "  agent-bridge logs    - View logs"
echo "  agent-bridge --help  - Help"
echo ""
