#!/bin/bash

# =================================
# Legal MCP Server - Enterprise Setup
# =================================
# Quick setup script for enterprise features

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

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

# Print banner
echo -e "${BLUE}"
echo "================================================="
echo "🏢 Legal MCP Server - Enterprise Setup"
echo "================================================="
echo -e "${NC}"

# Check if Node.js is installed
if ! command -v node &> /dev/null; then
    echo -e "${RED}❌ Node.js is not installed. Please install Node.js 18+ first.${NC}"
    exit 1
fi

# Check Node.js version
NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 18 ]; then
    echo -e "${RED}❌ Node.js 18+ is required. Found version: $(node -v)${NC}"
    exit 1
fi

echo -e "${GREEN}✅ Node.js $(node -v) detected${NC}"

# Function to prompt for yes/no
prompt_yes_no() {
    local question="$1"
    local default="$2"
    local answer
    
    while true; do
        if [ "$default" = "y" ]; then
            read -p "$(echo -e ${YELLOW}${question} [Y/n]: ${NC})" answer
            answer=${answer:-y}
        else
            read -p "$(echo -e ${YELLOW}${question} [y/N]: ${NC})" answer
            answer=${answer:-n}
        fi
        
        case $answer in
            [Yy]* ) return 0;;
            [Nn]* ) return 1;;
            * ) echo "Please answer yes or no.";;
        esac
    done
}

# Function to create .env file
create_env_file() {
    local env_file="$PROJECT_ROOT/.env"
    
    echo -e "${BLUE}📝 Creating environment configuration...${NC}"
    
    # Start with basic configuration
    cat > "$env_file" << EOF
# Legal MCP Server - Enterprise Configuration
# Generated by setup script on $(date)

# Core Configuration
NODE_ENV=development
LOG_LEVEL=info
PORT=3001

# CourtListener API
COURTLISTENER_BASE_URL=https://www.courtlistener.com/api/rest/v3
EOF

    # Prompt for CourtListener API key
    echo -e "${YELLOW}🔑 CourtListener API Configuration${NC}"
    read -p "Enter your CourtListener API key (optional): " courtlistener_key
    if [ -n "$courtlistener_key" ]; then
        echo "COURTLISTENER_API_KEY=$courtlistener_key" >> "$env_file"
    else
        echo "# COURTLISTENER_API_KEY=your_api_key_here" >> "$env_file"
    fi
    
    echo "" >> "$env_file"
    echo "# =================================" >> "$env_file"
    echo "# ENTERPRISE FEATURES" >> "$env_file"
    echo "# =================================" >> "$env_file"
    echo "" >> "$env_file"

    # Authentication
    if prompt_yes_no "🔐 Enable API key authentication?" "n"; then
        echo "# Authentication & Authorization" >> "$env_file"
        echo "SECURITY_AUTHENTICATION_ENABLED=true" >> "$env_file"
        
        read -p "Enter API key for authentication (will generate if empty): " api_key
        if [ -z "$api_key" ]; then
            api_key="legal-mcp-$(openssl rand -hex 16)"
            echo -e "${GREEN}📝 Generated API key: $api_key${NC}"
        fi
        echo "SECURITY_AUTHENTICATION_API_KEY=$api_key" >> "$env_file"
        echo "" >> "$env_file"
    fi

    # Input Sanitization
    if prompt_yes_no "🛡️  Enable input sanitization (recommended for production)?" "y"; then
        echo "# Input Sanitization" >> "$env_file"
        echo "SECURITY_SANITIZATION_ENABLED=true" >> "$env_file"
        echo "SECURITY_SANITIZATION_XSS_PROTECTION=true" >> "$env_file"
        echo "SECURITY_SANITIZATION_INJECTION_PROTECTION=true" >> "$env_file"
        echo "" >> "$env_file"
    fi

    # Audit Logging
    if prompt_yes_no "📝 Enable audit logging for compliance?" "n"; then
        echo "# Audit Logging" >> "$env_file"
        echo "AUDIT_ENABLED=true" >> "$env_file"
        echo "AUDIT_LOG_REQUESTS=true" >> "$env_file"
        echo "AUDIT_LOG_RESPONSES=false" >> "$env_file"
        echo "AUDIT_RETENTION_DAYS=90" >> "$env_file"
        echo "" >> "$env_file"
    fi

    # Response Compression
    if prompt_yes_no "🗜️  Enable response compression?" "y"; then
        echo "# Response Compression" >> "$env_file"
        echo "COMPRESSION_ENABLED=true" >> "$env_file"
        echo "COMPRESSION_THRESHOLD=1024" >> "$env_file"
        echo "COMPRESSION_LEVEL=6" >> "$env_file"
        echo "" >> "$env_file"
    fi

    # Rate Limiting
    if prompt_yes_no "🚦 Enable per-client rate limiting?" "y"; then
        echo "# Per-Client Rate Limiting" >> "$env_file"
        echo "RATE_LIMITING_PER_CLIENT_ENABLED=true" >> "$env_file"
        echo "RATE_LIMITING_PER_CLIENT_REQUESTS_PER_MINUTE=100" >> "$env_file"
        echo "RATE_LIMITING_PER_CLIENT_BURST_SIZE=20" >> "$env_file"
        echo "" >> "$env_file"
    fi

    # Circuit Breakers
    if prompt_yes_no "⚡ Enable circuit breakers for resilience?" "y"; then
        echo "# Circuit Breakers" >> "$env_file"
        echo "CIRCUIT_BREAKER_ENABLED=true" >> "$env_file"
        echo "CIRCUIT_BREAKER_FAILURE_THRESHOLD=5" >> "$env_file"
        echo "CIRCUIT_BREAKER_TIMEOUT=60000" >> "$env_file"
        echo "" >> "$env_file"
    fi

    # Graceful Shutdown
    if prompt_yes_no "🔄 Enable graceful shutdown?" "y"; then
        echo "# Graceful Shutdown" >> "$env_file"
        echo "GRACEFUL_SHUTDOWN_ENABLED=true" >> "$env_file"
        echo "GRACEFUL_SHUTDOWN_TIMEOUT=30000" >> "$env_file"
        echo "" >> "$env_file"
    fi

    # Basic cache and metrics
    echo "# Cache Configuration" >> "$env_file"
    echo "CACHE_ENABLED=true" >> "$env_file"
    echo "CACHE_TTL_SECONDS=3600" >> "$env_file"
    echo "" >> "$env_file"
    echo "# Metrics & Monitoring" >> "$env_file"
    echo "METRICS_ENABLED=true" >> "$env_file"
    echo "METRICS_PORT=3001" >> "$env_file"
    echo "HEALTH_ENABLED=true" >> "$env_file"

    echo -e "${GREEN}✅ Environment configuration saved to .env${NC}"
}

# Function to install dependencies
install_dependencies() {
    echo -e "${BLUE}📦 Installing dependencies...${NC}"
    
    cd "$PROJECT_ROOT"
    
    if command -v pnpm &> /dev/null; then
        echo "Using pnpm..."
        pnpm install
    elif command -v yarn &> /dev/null; then
        echo "Using yarn..."
        yarn install
    else
        echo "Using npm..."
        npm install
    fi
    
    echo -e "${GREEN}✅ Dependencies installed${NC}"
}

# Function to build the project
build_project() {
    echo -e "${BLUE}🔨 Building project...${NC}"
    
    cd "$PROJECT_ROOT"
    
    if command -v pnpm &> /dev/null; then
        pnpm build
    elif command -v yarn &> /dev/null; then
        yarn build
    else
        npm run build
    fi
    
    echo -e "${GREEN}✅ Project built successfully${NC}"
}

# Function to run health check
run_health_check() {
    echo -e "${BLUE}🏥 Running health check...${NC}"
    
    # Start server in background
    cd "$PROJECT_ROOT"
    npm start &
    SERVER_PID=$!
    
    # Wait for server to start
    echo "Waiting for server to start..."
    sleep 5
    
    # Check health endpoint
    if curl -f http://localhost:3001/health > /dev/null 2>&1; then
        echo -e "${GREEN}✅ Server is healthy and responding${NC}"
        
        # Show enterprise features status
        echo -e "${BLUE}🏢 Enterprise Features Status:${NC}"
        curl -s http://localhost:3001/health | jq '.enterprise_features' 2>/dev/null || echo "Health endpoint available"
    else
        echo -e "${RED}❌ Server health check failed${NC}"
    fi
    
    # Stop server
    kill $SERVER_PID 2>/dev/null || true
    wait $SERVER_PID 2>/dev/null || true
}

# Function to show usage instructions
show_usage_instructions() {
    echo -e "${BLUE}"
    echo "================================================="
    echo "🎉 Setup Complete!"
    echo "================================================="
    echo -e "${NC}"
    
    echo -e "${GREEN}✅ Enterprise Legal MCP Server is ready!${NC}"
    echo ""
    echo -e "${YELLOW}📋 What's been configured:${NC}"
    echo "   • Environment variables in .env file"
    echo "   • Enterprise features based on your choices"
    echo "   • Dependencies installed and project built"
    echo ""
    echo -e "${YELLOW}🚀 To start the server:${NC}"
    echo "   npm start"
    echo ""
    echo -e "${YELLOW}🔍 To check status:${NC}"
    echo "   curl http://localhost:3001/health"
    echo ""
    echo -e "${YELLOW}🛠️  To modify configuration:${NC}"
    echo "   Edit the .env file and restart the server"
    echo ""
    echo -e "${YELLOW}📖 For more information:${NC}"
    echo "   • See ENTERPRISE_FEATURES.md for detailed configuration"
    echo "   • See ENTERPRISE_SUMMARY.md for implementation overview"
    echo "   • Run node enterprise-demo.js for feature demonstration"
    echo ""
    echo -e "${BLUE}🔗 Repository: https://github.com/blakeox/courtlistener-mcp${NC}"
}

# Main setup flow
main() {
    echo -e "${BLUE}🚀 Starting enterprise setup...${NC}"
    echo ""
    
    # Check if .env already exists
    if [ -f "$PROJECT_ROOT/.env" ]; then
        if prompt_yes_no "⚠️  .env file already exists. Overwrite?" "n"; then
            create_env_file
        else
            echo -e "${YELLOW}📝 Using existing .env file${NC}"
        fi
    else
        create_env_file
    fi
    
    echo ""
    
    # Install dependencies if needed
    if [ ! -d "$PROJECT_ROOT/node_modules" ]; then
        install_dependencies
    else
        if prompt_yes_no "📦 Reinstall dependencies?" "n"; then
            install_dependencies
        fi
    fi
    
    echo ""
    
    # Build project
    if [ ! -d "$PROJECT_ROOT/dist" ]; then
        build_project
    else
        if prompt_yes_no "🔨 Rebuild project?" "y"; then
            build_project
        fi
    fi
    
    echo ""
    
    # Optional health check
    if prompt_yes_no "🏥 Run health check?" "y"; then
        run_health_check
    fi
    
    echo ""
    show_usage_instructions
}

# Run setup if script is executed directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi
