#!/bin/bash

# Comprehensive Health Check & Diagnostic Script
# Post-deployment validation with automated recovery suggestions
#
# This script can be run:
#   1. Standalone: ./scripts/health-check-comprehensive.sh
#   2. After deployment: Called by deploy-dev.sh
#   3. On-demand debugging: When issues are suspected
#
# Usage:
#   ./scripts/health-check-comprehensive.sh [OPTIONS]
#
# Options:
#   --fix          Attempt automated fixes for detected issues
#   --verbose      Show detailed output
#   --test-url=URL Test specific base URL (default: auto-detect)
#   --skip-http    Skip HTTP endpoint tests (useful for local dev)
#   --help         Show this help message

set -e  # Exit on error

# ==============================================================================
# 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 || {
    # Fallback if atoms not available
    log_info() { echo "[INFO] $*"; }
    log_success() { echo "[✓] $*"; }
    log_warning() { echo "[!] $*"; }
    log_error() { echo "[✗] $*"; }
    log_section() { echo ""; echo "=== $* ==="; echo ""; }
}

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

AUTO_FIX=false
VERBOSE=false
SKIP_HTTP=false
TEST_URL=""

show_help() {
    cat << EOF
Comprehensive Health Check & Diagnostic Script

Usage: $0 [OPTIONS]

Options:
  --fix          Attempt automated fixes for detected issues
  --verbose      Show detailed output and diagnostic info
  --test-url=URL Test specific base URL (e.g., https://dev-api.globalgala.com)
  --skip-http    Skip HTTP endpoint tests (useful for local development)
  --help         Show this help message

Examples:
  $0                                    # Standard health check
  $0 --fix                              # Health check with auto-fix
  $0 --test-url=https://dev-api.globalgala.com  # Test specific URL
  $0 --verbose                          # Detailed diagnostic output

Exit Codes:
  0  All checks passed
  1  Critical failures detected
  2  Warnings detected (non-critical)

EOF
    exit 0
}

for arg in "$@"; do
    case $arg in
        --fix)
            AUTO_FIX=true
            shift
            ;;
        --verbose)
            VERBOSE=true
            shift
            ;;
        --skip-http)
            SKIP_HTTP=true
            shift
            ;;
        --test-url=*)
            TEST_URL="${arg#*=}"
            shift
            ;;
        --help|-h)
            show_help
            ;;
        *)
            log_error "Unknown option: $arg"
            echo "Run with --help for usage information"
            exit 1
            ;;
    esac
done

# ==============================================================================
# GLOBAL STATE TRACKING
# ==============================================================================

CRITICAL_FAILURES=0
WARNINGS=0
CHECKS_PASSED=0
TOTAL_CHECKS=0

# Store issues for reporting at end
declare -a CRITICAL_ISSUES
declare -a WARNING_ISSUES
declare -a FIX_COMMANDS

track_check() {
    local result=$1
    local check_name=$2
    local issue_message=$3
    local fix_command=$4

    ((TOTAL_CHECKS++))

    if [[ $result -eq 0 ]]; then
        ((CHECKS_PASSED++))
        return 0
    elif [[ $result -eq 1 ]]; then
        ((CRITICAL_FAILURES++))
        CRITICAL_ISSUES+=("$check_name: $issue_message")
        if [[ -n "$fix_command" ]]; then
            FIX_COMMANDS+=("# Fix: $check_name")
            FIX_COMMANDS+=("$fix_command")
            FIX_COMMANDS+=("")
        fi
        return 1
    elif [[ $result -eq 2 ]]; then
        ((WARNINGS++))
        WARNING_ISSUES+=("$check_name: $issue_message")
        return 2
    fi
}

# ==============================================================================
# UTILITY FUNCTIONS
# ==============================================================================

# Check if running on server (has public URL)
is_server_environment() {
    [[ -n "$TEST_URL" ]] || [[ -f "/etc/cpanel" ]] || [[ -d "/usr/local/cpanel" ]]
}

# Detect base URL for testing
detect_base_url() {
    if [[ -n "$TEST_URL" ]]; then
        echo "$TEST_URL"
    elif [[ -f ".env" ]] && grep -q "APP_URL" .env; then
        grep "APP_URL" .env | cut -d'=' -f2 | tr -d '"' | tr -d "'"
    else
        echo "http://localhost:8000"
    fi
}

# Parse Laravel logs for recent errors (last 50 lines)
check_recent_laravel_errors() {
    local log_file="storage/logs/laravel-$(date +%Y-%m-%d).log"

    if [[ ! -f "$log_file" ]]; then
        return 0  # No log file = no errors today
    fi

    local error_count=$(tail -50 "$log_file" | grep -c "ERROR" || true)

    if [[ $error_count -gt 0 ]]; then
        if [[ "$VERBOSE" == "true" ]]; then
            log_warning "Found $error_count recent errors in Laravel logs:"
            tail -50 "$log_file" | grep "ERROR" | head -5
        fi
        return 2  # Warning
    fi

    return 0
}

# ==============================================================================
# CHECK 1: HTACCESS SYNTAX VALIDATION
# ==============================================================================

check_htaccess_syntax() {
    log_info "Checking .htaccess syntax..."

    if [[ ! -f "public/.htaccess" ]]; then
        track_check 1 ".htaccess File" "Missing public/.htaccess file" \
            "# Create default .htaccess from Laravel"
        return 1
    fi

    # Check for common syntax errors
    local issues_found=false

    # Check 1: env=HTTP_ORIGIN on separate line (causes 500 error)
    if grep -Pzo 'Header.*\n.*env=HTTP_ORIGIN' public/.htaccess > /dev/null 2>&1; then
        log_error ".htaccess syntax error: env=HTTP_ORIGIN on separate line"
        issues_found=true
    fi

    # Check 2: Invalid AddHandler format
    if grep -q "AddHandler application/x-httpd-ea-php[0-9]* \$" public/.htaccess; then
        log_error ".htaccess syntax error: AddHandler missing file extension"
        issues_found=true
    fi

    # Check 3: Wildcard CORS with credentials
    if grep -q 'Access-Control-Allow-Origin "\*"' public/.htaccess && \
       grep -q 'Access-Control-Allow-Credentials "true"' public/.htaccess; then
        log_warning ".htaccess CORS warning: Wildcard origin incompatible with credentials mode"
        track_check 2 ".htaccess CORS" "Wildcard CORS with credentials will fail" \
            "# Update .htaccess to use specific origins instead of *"
        return 2
    fi

    if [[ "$issues_found" == "true" ]]; then
        track_check 1 ".htaccess Syntax" "Syntax errors detected that will cause 500 errors" \
            "# Review public/.htaccess file and fix syntax errors
# Common issues: env=HTTP_ORIGIN on wrong line, invalid AddHandler format
# See: /usr/local/apache/logs/error_log for Apache errors"
        return 1
    fi

    log_success ".htaccess syntax OK"
    track_check 0 ".htaccess Syntax"
    return 0
}

# ==============================================================================
# CHECK 2: COMPOSER AUTOLOAD VALIDATION
# ==============================================================================

check_composer_autoload() {
    log_info "Checking composer autoload..."

    # Try to load a Laravel class
    if ! php -r "require 'vendor/autoload.php'; class_exists('Illuminate\Foundation\Application');" 2>/dev/null; then
        log_error "Composer autoload is stale or broken"
        track_check 1 "Composer Autoload" "Cannot load Laravel classes - autoload cache is stale" \
            "composer dump-autoload --optimize"
        return 1
    fi

    log_success "Composer autoload OK"
    track_check 0 "Composer Autoload"
    return 0
}

# ==============================================================================
# CHECK 3: LARAVEL BOOT TEST
# ==============================================================================

check_laravel_boot() {
    log_info "Checking Laravel application boot..."

    if ! php artisan --version > /dev/null 2>&1; then
        log_error "Laravel cannot boot"

        # Try to identify the issue
        local error_output=$(php artisan --version 2>&1 || true)

        if echo "$error_output" | grep -q "Class.*not found"; then
            track_check 1 "Laravel Boot" "Class not found error - composer autoload is stale" \
                "composer dump-autoload --optimize && php artisan config:cache"
        else
            track_check 1 "Laravel Boot" "Application boot failed: $error_output" \
                "# Check storage/logs/laravel-$(date +%Y-%m-%d).log for details
php artisan config:clear
php artisan cache:clear
composer dump-autoload --optimize"
        fi
        return 1
    fi

    log_success "Laravel boots successfully"
    track_check 0 "Laravel Boot"
    return 0
}

# ==============================================================================
# CHECK 4: CACHE STATUS
# ==============================================================================

check_cache_health() {
    log_info "Checking cache status..."

    local issues=false

    # Check for stale bootstrap cache
    if [[ -f "bootstrap/cache/config.php" ]]; then
        local cache_age=$(($(date +%s) - $(stat -f %m "bootstrap/cache/config.php" 2>/dev/null || stat -c %Y "bootstrap/cache/config.php")))
        if [[ $cache_age -gt 86400 ]]; then
            log_warning "Config cache is older than 24 hours"
            issues=true
        fi
    else
        log_warning "Config cache not found (will be slower)"
        issues=true
    fi

    if [[ "$issues" == "true" ]]; then
        track_check 2 "Cache Health" "Cache may be stale or missing" \
            "php artisan config:cache"
        return 2
    fi

    log_success "Cache status OK"
    track_check 0 "Cache Health"
    return 0
}

# ==============================================================================
# CHECK 5: HTTP ENDPOINT TESTS
# ==============================================================================

check_http_endpoints() {
    if [[ "$SKIP_HTTP" == "true" ]]; then
        log_info "Skipping HTTP endpoint tests (--skip-http flag)"
        return 0
    fi

    log_info "Testing HTTP endpoints..."

    local base_url=$(detect_base_url)
    local endpoints=(
        "/api/events:GET:List events"
        "/health:GET:Health check"
    )

    local failed=false

    for endpoint_def in "${endpoints[@]}"; do
        IFS=':' read -r path method description <<< "$endpoint_def"
        local url="${base_url}${path}"

        if [[ "$VERBOSE" == "true" ]]; then
            log_info "  Testing $method $url ($description)"
        fi

        local response=$(curl -s -w "\n%{http_code}" -X "$method" "$url" 2>&1 || echo "000")
        local http_code=$(echo "$response" | tail -1)
        local body=$(echo "$response" | sed '$d')

        case $http_code in
            200|201)
                if [[ "$VERBOSE" == "true" ]]; then
                    log_success "  $description: HTTP $http_code ✓"
                fi
                ;;
            500)
                log_error "  $description: HTTP 500 - Server error"
                if [[ "$VERBOSE" == "true" ]] && echo "$body" | grep -q "Invalid command"; then
                    log_error "    Likely .htaccess syntax error"
                fi
                failed=true
                ;;
            000)
                log_error "  $description: Connection failed"
                failed=true
                ;;
            *)
                log_warning "  $description: HTTP $http_code"
                ;;
        esac
    done

    if [[ "$failed" == "true" ]]; then
        track_check 1 "HTTP Endpoints" "One or more endpoints returning errors" \
            "# Check Laravel logs and Apache error logs
# For 500 errors, check: tail -50 /usr/local/apache/logs/error_log
# For Laravel errors: tail -50 storage/logs/laravel-$(date +%Y-%m-%d).log"
        return 1
    fi

    log_success "All HTTP endpoints responding"
    track_check 0 "HTTP Endpoints"
    return 0
}

# ==============================================================================
# CHECK 6: CORS HEADERS VALIDATION
# ==============================================================================

check_cors_headers() {
    if [[ "$SKIP_HTTP" == "true" ]]; then
        log_info "Skipping CORS check (--skip-http flag)"
        return 0
    fi

    log_info "Checking CORS headers..."

    local base_url=$(detect_base_url)
    local test_origin="https://admin.dev.globalgala.com"

    local cors_response=$(curl -s -I -X OPTIONS "${base_url}/api/events" \
        -H "Origin: $test_origin" \
        -H "Access-Control-Request-Method: GET" 2>&1 || true)

    if ! echo "$cors_response" | grep -qi "Access-Control-Allow-Origin"; then
        log_error "CORS headers not present in response"
        track_check 1 "CORS Headers" "Access-Control-Allow-Origin header missing" \
            "# Check public/.htaccess CORS configuration
# Ensure mod_headers is enabled
# Check Apache config allows .htaccess overrides"
        return 1
    fi

    if echo "$cors_response" | grep -q "Access-Control-Allow-Origin: \*" && \
       echo "$cors_response" | grep -q "Access-Control-Allow-Credentials: true"; then
        log_error "CORS misconfiguration: Wildcard origin with credentials"
        track_check 1 "CORS Configuration" "Cannot use wildcard * with credentials: true" \
            "# Update public/.htaccess to use specific origins
# Replace 'Access-Control-Allow-Origin: *' with whitelisted origins"
        return 1
    fi

    log_success "CORS headers configured correctly"
    track_check 0 "CORS Headers"
    return 0
}

# ==============================================================================
# CHECK 7: RECENT LOG ERRORS
# ==============================================================================

check_log_errors() {
    log_info "Checking recent log errors..."

    check_recent_laravel_errors
    local result=$?

    if [[ $result -eq 2 ]]; then
        track_check 2 "Laravel Logs" "Recent errors detected in logs" \
            "# Review logs: tail -50 storage/logs/laravel-$(date +%Y-%m-%d).log"
        return 2
    fi

    log_success "No recent critical errors in logs"
    track_check 0 "Laravel Logs"
    return 0
}

# ==============================================================================
# CHECK 8: QUEUE WORKER STATUS
# ==============================================================================

check_queue_worker() {
    log_info "Checking queue worker..."

    # Check if queue worker is running
    if pgrep -f "queue:work" > /dev/null; then
        log_success "Queue worker is running"
        track_check 0 "Queue Worker"
        return 0
    else
        log_warning "Queue worker not running (emails will not send)"
        track_check 2 "Queue Worker" "No queue worker process detected" \
            "./scripts/start-queue-worker.sh"
        return 2
    fi
}

# ==============================================================================
# AUTOMATED FIX EXECUTION
# ==============================================================================

execute_auto_fixes() {
    if [[ "$AUTO_FIX" != "true" ]]; then
        return 0
    fi

    if [[ ${#FIX_COMMANDS[@]} -eq 0 ]]; then
        log_info "No automated fixes needed"
        return 0
    fi

    log_section "Attempting Automated Fixes"

    for cmd in "${FIX_COMMANDS[@]}"; do
        if [[ "$cmd" =~ ^#.* ]]; then
            log_info "$cmd"
        elif [[ -z "$cmd" ]]; then
            echo ""
        else
            log_info "Running: $cmd"
            if eval "$cmd"; then
                log_success "✓ Fix applied"
            else
                log_error "✗ Fix failed"
            fi
        fi
    done
}

# ==============================================================================
# MAIN EXECUTION
# ==============================================================================

main() {
    log_section "Comprehensive Health Check"

    echo "Configuration:"
    echo "  Project Root:    $PROJECT_ROOT"
    echo "  Auto-Fix:        $AUTO_FIX"
    echo "  Verbose:         $VERBOSE"
    echo "  Base URL:        $(detect_base_url)"
    echo ""

    # Run all checks
    check_htaccess_syntax || true
    check_composer_autoload || true
    check_laravel_boot || true
    check_cache_health || true
    check_http_endpoints || true
    check_cors_headers || true
    check_log_errors || true
    check_queue_worker || true

    # Execute auto-fixes if requested
    execute_auto_fixes

    # Final report
    log_section "Health Check Summary"

    echo "Results:"
    echo "  Total Checks:      $TOTAL_CHECKS"
    echo "  Passed:            $CHECKS_PASSED"
    echo "  Warnings:          $WARNINGS"
    echo "  Critical Failures: $CRITICAL_FAILURES"
    echo ""

    # Show critical issues
    if [[ $CRITICAL_FAILURES -gt 0 ]]; then
        log_error "Critical Issues Detected:"
        for issue in "${CRITICAL_ISSUES[@]}"; do
            echo "  ✗ $issue"
        done
        echo ""
    fi

    # Show warnings
    if [[ $WARNINGS -gt 0 ]]; then
        log_warning "Warnings:"
        for issue in "${WARNING_ISSUES[@]}"; do
            echo "  ! $issue"
        done
        echo ""
    fi

    # Show fix commands
    if [[ ${#FIX_COMMANDS[@]} -gt 0 ]] && [[ "$AUTO_FIX" != "true" ]]; then
        log_section "Suggested Fixes"
        echo "Run these commands to fix detected issues:"
        echo ""
        for cmd in "${FIX_COMMANDS[@]}"; do
            echo "$cmd"
        done
        echo ""
        log_info "Or run with --fix to apply automated fixes"
        echo ""
    fi

    # Exit with appropriate code
    if [[ $CRITICAL_FAILURES -gt 0 ]]; then
        log_error "❌ Health check FAILED with $CRITICAL_FAILURES critical issue(s)"
        exit 1
    elif [[ $WARNINGS -gt 0 ]]; then
        log_warning "⚠️  Health check completed with $WARNINGS warning(s)"
        exit 2
    else
        log_success "✅ Health check PASSED - All systems operational!"
        exit 0
    fi
}

# Run main function
main "$@"
