#!/bin/bash

# Veza Fixtures Installation Script
# Installs and configures the complete fixtures system

set -e

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

# Configuration
FIXTURES_DIR="fixtures"
NODE_VERSION="18"

# Helper functions
log_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

log_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

log_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

log_error() {
    echo -e "${RED}❌ $1${NC}"
}

check_command() {
    if ! command -v $1 &> /dev/null; then
        log_error "$1 is required but not installed"
        return 1
    fi
    return 0
}

# Main installation function
main() {
    log_info "🎵 Installing Veza Fixtures System..."
    
    # Check prerequisites
    log_info "Checking prerequisites..."
    
    if ! check_command "node"; then
        log_error "Node.js is required. Please install Node.js ${NODE_VERSION} or later."
        exit 1
    fi
    
    if ! check_command "npm"; then
        log_error "npm is required. Please install npm."
        exit 1
    fi
    
    # Check Node.js version
    NODE_CURRENT=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
    if [ "$NODE_CURRENT" -lt "$NODE_VERSION" ]; then
        log_error "Node.js ${NODE_VERSION} or later is required. Current version: $(node -v)"
        exit 1
    fi
    
    log_success "Prerequisites check passed"
    
    # Navigate to fixtures directory
    if [ ! -d "$FIXTURES_DIR" ]; then
        log_error "Fixtures directory not found. Please run this script from the project root."
        exit 1
    fi
    
    cd "$FIXTURES_DIR"
    
    # Install dependencies
    log_info "Installing Node.js dependencies..."
    npm install
    log_success "Dependencies installed"
    
    # Build TypeScript
    log_info "Building TypeScript..."
    npm run build
    log_success "TypeScript built successfully"
    
    # Make CLI executable
    log_info "Setting up CLI tool..."
    chmod +x tools/cli/index.ts
    
    # Create global symlink (optional)
    if command -v npm &> /dev/null; then
        log_info "Creating global CLI link..."
        npm link 2>/dev/null || log_warning "Could not create global link. You may need sudo privileges."
    fi
    
    # Setup environment file
    log_info "Setting up environment configuration..."
    if [ ! -f ".env" ]; then
        cp "../env.example" ".env" 2>/dev/null || {
            cat > .env << EOF
# Veza Fixtures Environment Configuration

# Database Configuration
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=veza
DB_PASSWORD=veza_password
DB_MAIN=veza_dev
DB_CHAT=veza_chat
DB_TEST=veza_test

# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=

# Fixtures Configuration
FIXTURES_SEED=veza-platform-2025
FIXTURES_LOCALE=fr
EOF
        }
        log_success "Environment file created"
    else
        log_info "Environment file already exists"
    fi
    
    # Create assets directories
    log_info "Creating asset directories..."
    mkdir -p assets/audio
    mkdir -p assets/images
    mkdir -p exports
    log_success "Asset directories created"
    
    # Run initial validation
    log_info "Running system validation..."
    if npm run validate 2>/dev/null; then
        log_success "System validation passed"
    else
        log_warning "System validation had warnings (this is normal for first install)"
    fi
    
    # Display success message and usage instructions
    echo
    log_success "🎉 Veza Fixtures System installed successfully!"
    echo
    log_info "Usage examples:"
    echo "  📊 Generate fixtures:     npm run generate -- --env development"
    echo "  🌱 Seed services:        npm run seed -- --service all"
    echo "  🔍 Validate data:        npm run validate"
    echo "  📋 List scenarios:       npm run scenario -- --list"
    echo "  ℹ️  Show status:          npm run status"
    echo
    log_info "CLI tool (if globally linked):"
    echo "  veza-fixtures generate --env development"
    echo "  veza-fixtures seed --service web"
    echo "  veza-fixtures scenario --run onboarding"
    echo
    log_info "Configuration:"
    echo "  📁 Edit .env file to customize database and service connections"
    echo "  🎯 Use different environments: development, testing, staging, demo"
    echo
    log_info "Next steps:"
    echo "  1. Configure your database connections in .env"
    echo "  2. Start your services (PostgreSQL, Redis)"
    echo "  3. Run: npm run generate -- --env development"
    echo "  4. Run: npm run seed -- --service all"
    echo
}

# Handle script arguments
case "${1:-install}" in
    "install")
        main
        ;;
    "uninstall")
        log_info "Uninstalling Veza Fixtures System..."
        cd "$FIXTURES_DIR"
        
        # Remove global link
        npm unlink 2>/dev/null || true
        
        # Clean build artifacts
        rm -rf dist/
        rm -rf node_modules/
        
        # Clean exports
        rm -rf exports/*
        
        log_success "Uninstalled successfully"
        ;;
    "update")
        log_info "Updating Veza Fixtures System..."
        cd "$FIXTURES_DIR"
        
        # Update dependencies
        npm update
        
        # Rebuild
        npm run build
        
        log_success "Updated successfully"
        ;;
    "doctor")
        log_info "Running system diagnostics..."
        cd "$FIXTURES_DIR"
        
        # Check Node.js
        echo "Node.js version: $(node -v)"
        echo "npm version: $(npm -v)"
        
        # Check dependencies
        if [ -f "package.json" ]; then
            log_info "Checking dependencies..."
            npm list --depth=0 2>/dev/null || log_warning "Some dependencies may be missing"
        fi
        
        # Check environment
        if [ -f ".env" ]; then
            log_info "Environment file exists"
        else
            log_warning "Environment file missing"
        fi
        
        # Check build
        if [ -d "dist" ]; then
            log_info "Build directory exists"
        else
            log_warning "Build directory missing - run 'npm run build'"
        fi
        
        # Test CLI
        if npm run status >/dev/null 2>&1; then
            log_success "CLI tool working"
        else
            log_warning "CLI tool may have issues"
        fi
        
        log_success "Diagnostics complete"
        ;;
    "help")
        echo "Veza Fixtures Installation Script"
        echo
        echo "Usage: $0 [command]"
        echo
        echo "Commands:"
        echo "  install     Install the fixtures system (default)"
        echo "  uninstall   Remove the fixtures system"
        echo "  update      Update dependencies and rebuild"
        echo "  doctor      Run system diagnostics"
        echo "  help        Show this help message"
        echo
        ;;
    *)
        log_error "Unknown command: $1"
        echo "Use '$0 help' for usage information"
        exit 1
        ;;
esac