#!/bin/bash

# Emergency Reset Script
# Nuclear option for recovering from deployment failures
#
# This script performs a comprehensive reset of all caches and autoload
# systems to recover from deployment issues.
#
# ⚠️  WARNING: This is a destructive operation that clears all caches
#
# Usage:
#   ./scripts/emergency-reset.sh [OPTIONS]
#
# Options:
#   --full           Full reset including vendor reinstall (takes longer)
#   --backup-first   Create database backup before reset
#   --yes            Skip confirmation prompts
#   --help           Show this help message

set -e

# ==============================================================================
# INITIALIZATION
# ==============================================================================

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

# Load deployment libraries
source "$SCRIPT_DIR/_deploy-atoms.sh" 2>/dev/null || {
    log_info() { echo "[INFO] $*"; }
    log_success() { echo "[✓] $*"; }
    log_warning() { echo "[!] $*"; }
    log_error() { echo "[✗] $*"; }
    log_section() { echo ""; echo "=== $* ==="; echo ""; }
}

# ==============================================================================
# ARGUMENT PARSING
# ==============================================================================

FULL_RESET=false
BACKUP_FIRST=false
SKIP_CONFIRM=false

show_help() {
    cat << EOF
Emergency Reset Script - Nuclear Option for Deployment Recovery

⚠️  WARNING: This script performs destructive cache clearing operations

Usage: $0 [OPTIONS]

Options:
  --full           Full reset including composer vendor reinstall (slower)
  --backup-first   Create database backup before reset
  --yes            Skip confirmation prompts (use with caution)
  --help           Show this help message

What This Script Does:
  1. Clears all Laravel caches (config, route, view, event, compiled)
  2. Removes all bootstrap cache files
  3. Rebuilds composer autoload (--optimize)
  4. Optionally reinstalls composer dependencies (--full)
  5. Rebuilds config cache
  6. Reports success/failure

When To Use This:
  - After deployment when Laravel won't boot
  - "Class not found" errors after git pull
  - Mysterious 500 errors after cache operations
  - Composer dependency conflicts
  - Stale autoload cache issues

Examples:
  $0                      # Standard cache reset
  $0 --backup-first       # Backup database first
  $0 --full               # Full reset with vendor reinstall
  $0 --yes --full         # Full reset without confirmation

EOF
    exit 0
}

for arg in "$@"; do
    case $arg in
        --full)
            FULL_RESET=true
            shift
            ;;
        --backup-first)
            BACKUP_FIRST=true
            shift
            ;;
        --yes|-y)
            SKIP_CONFIRM=true
            shift
            ;;
        --help|-h)
            show_help
            ;;
        *)
            log_error "Unknown option: $arg"
            echo "Run with --help for usage information"
            exit 1
            ;;
    esac
done

# ==============================================================================
# CONFIRMATION
# ==============================================================================

if [[ "$SKIP_CONFIRM" != "true" ]]; then
    log_warning "Emergency Reset - This will clear all caches"
    echo ""
    echo "Operations to perform:"
    echo "  - Clear all Laravel caches"
    echo "  - Remove bootstrap cache"
    echo "  - Rebuild composer autoload"
    if [[ "$FULL_RESET" == "true" ]]; then
        echo "  - Reinstall composer dependencies (--full)"
    fi
    if [[ "$BACKUP_FIRST" == "true" ]]; then
        echo "  - Create database backup first"
    fi
    echo ""
    read -p "Continue? (y/n) " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_info "Aborted by user"
        exit 0
    fi
fi

# ==============================================================================
# BACKUP (IF REQUESTED)
# ==============================================================================

if [[ "$BACKUP_FIRST" == "true" ]]; then
    log_section "Creating Database Backup"

    if [[ -f "$SCRIPT_DIR/backup-db.sh" ]]; then
        if "$SCRIPT_DIR/backup-db.sh"; then
            log_success "Database backup created"
        else
            log_error "Database backup failed"
            exit 1
        fi
    else
        log_warning "Backup script not found, skipping backup"
    fi
fi

# ==============================================================================
# EMERGENCY RESET EXECUTION
# ==============================================================================

log_section "Emergency Reset - Starting"

RESET_START=$(date +%s)
OPERATIONS_FAILED=0

# Operation 1: Clear application caches
log_info "[1/7] Clearing application cache..."
if php artisan cache:clear 2>/dev/null; then
    log_success "Application cache cleared"
else
    log_warning "Application cache clear failed (may not exist)"
fi

# Operation 2: Clear config cache
log_info "[2/7] Clearing config cache..."
if php artisan config:clear 2>/dev/null; then
    log_success "Config cache cleared"
else
    log_warning "Config cache clear failed"
    ((OPERATIONS_FAILED++))
fi

# Operation 3: Clear route cache
log_info "[3/7] Clearing route cache..."
if php artisan route:clear 2>/dev/null; then
    log_success "Route cache cleared"
else
    log_warning "Route cache clear failed"
fi

# Operation 4: Clear view cache
log_info "[4/7] Clearing view cache..."
if php artisan view:clear 2>/dev/null; then
    log_success "View cache cleared"
else
    log_warning "View cache clear failed (views directory may not exist)"
fi

# Operation 5: Clear event cache
log_info "[5/7] Clearing event cache..."
if php artisan event:clear 2>/dev/null; then
    log_success "Event cache cleared"
else
    log_warning "Event cache clear failed"
fi

# Operation 6: Remove bootstrap cache files
log_info "[6/7] Removing bootstrap cache files..."
if rm -rf bootstrap/cache/*.php 2>/dev/null; then
    log_success "Bootstrap cache removed"
else
    log_warning "No bootstrap cache files found"
fi

# Operation 7: Rebuild composer autoload
log_info "[7/7] Rebuilding composer autoload..."
if composer dump-autoload --optimize --no-interaction; then
    log_success "Composer autoload rebuilt"
else
    log_error "Composer autoload rebuild FAILED"
    ((OPERATIONS_FAILED++))
fi

# Operation 8 (Optional): Full composer reinstall
if [[ "$FULL_RESET" == "true" ]]; then
    log_info "[FULL] Removing and reinstalling vendor directory..."

    # Remove vendor (keep composer.lock)
    if [[ -d "vendor" ]]; then
        rm -rf vendor
        log_success "Vendor directory removed"
    fi

    # Reinstall dependencies
    log_info "Reinstalling composer dependencies (this may take a few minutes)..."
    if composer install --no-interaction --prefer-dist --optimize-autoloader; then
        log_success "Composer dependencies reinstalled"
    else
        log_error "Composer install FAILED"
        ((OPERATIONS_FAILED++))
    fi
fi

# ==============================================================================
# REBUILD CACHES
# ==============================================================================

log_section "Rebuilding Caches"

# Rebuild config cache
log_info "Rebuilding config cache..."
if php artisan config:cache; then
    log_success "Config cache rebuilt"
else
    log_error "Config cache rebuild FAILED"
    ((OPERATIONS_FAILED++))
fi

# ==============================================================================
# VERIFICATION
# ==============================================================================

log_section "Verification"

# Test 1: Laravel can boot
log_info "Testing Laravel boot..."
if php artisan --version > /dev/null 2>&1; then
    log_success "Laravel boots successfully"
else
    log_error "Laravel STILL cannot boot - manual intervention required"
    ((OPERATIONS_FAILED++))
fi

# Test 2: Composer autoload works
log_info "Testing composer autoload..."
if php -r "require 'vendor/autoload.php'; class_exists('Illuminate\Foundation\Application');" 2>/dev/null; then
    log_success "Composer autoload working"
else
    log_error "Composer autoload STILL broken - manual intervention required"
    ((OPERATIONS_FAILED++))
fi

# ==============================================================================
# SUMMARY
# ==============================================================================

RESET_END=$(date +%s)
RESET_DURATION=$((RESET_END - RESET_START))

log_section "Emergency Reset Complete"

echo "Duration: ${RESET_DURATION}s"
echo ""

if [[ $OPERATIONS_FAILED -eq 0 ]]; then
    log_success "✅ All operations completed successfully!"
    echo ""
    log_info "Next steps:"
    echo "  1. Test your application: curl http://localhost:8000/health"
    echo "  2. Check Laravel logs: tail -f storage/logs/laravel-*.log"
    echo "  3. Run health check: ./scripts/health-check-comprehensive.sh"
    echo ""
    exit 0
else
    log_error "❌ $OPERATIONS_FAILED operation(s) failed"
    echo ""
    log_info "Manual recovery steps:"
    echo "  1. Check Laravel logs: tail -50 storage/logs/laravel-$(date +%Y-%m-%d).log"
    echo "  2. Verify .env configuration"
    echo "  3. Check file permissions: ls -la storage bootstrap/cache"
    echo "  4. Try full reset: $0 --full"
    echo "  5. Contact deployment team if issues persist"
    echo ""
    exit 1
fi
