#!/bin/bash

# Ready or Not Crash Diagnostic Script
# Gathers all relevant crash information

set -e

GAME_ID="1144200"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

check_system_prerequisites() {
    log_info "=== System Prerequisites Check ==="
    
    # Check kernel version
    log_info "Kernel: $(uname -r)"
    
    # Check graphics drivers
    if command -v nvidia-smi >/dev/null 2>&1; then
        local gpu_info=$(nvidia-smi --query-gpu=name,driver_version --format=csv,noheader,nounits | head -1)
        log_info "GPU: $gpu_info"
    fi
    
    # Check Vulkan
    if command -v vulkaninfo >/dev/null 2>&1; then
        local vulkan_devices=$(vulkaninfo --summary 2>/dev/null | grep "GPU id" | wc -l)
        log_info "Vulkan devices: $vulkan_devices"
    fi
    
    # Check Steam process
    if pgrep -f steam >/dev/null; then
        log_success "Steam is running"
    else
        log_warning "Steam is not running"
    fi
    
    echo
}

check_proton_versions() {
    log_info "=== Available Proton Versions ==="
    
    local steam_dirs=(
        "$HOME/.steam/steam/steamapps/common"
        "$HOME/.local/share/Steam/steamapps/common"
    )
    
    for steam_dir in "${steam_dirs[@]}"; do
        if [ -d "$steam_dir" ]; then
            log_info "Proton versions in $steam_dir:"
            ls "$steam_dir" 2>/dev/null | grep -i proton || log_warning "No Proton versions found"
        fi
    done
    
    echo
}

test_basic_compatibility() {
    log_info "=== Testing Basic Wine/Proton Compatibility ==="
    
    # Test basic Wine functionality
    log_info "Testing Wine with simple Windows executable..."
    
    # Create a simple test script
    cat > /tmp/wine_test.sh << 'EOF'
#!/bin/bash
export WINEPREFIX="/tmp/wine_test_prefix"
export PROTON_LOG=1

# Try to run a simple Windows command
timeout 10s wine cmd /c "echo Wine test successful" 2>&1 | head -5
EOF
    
    chmod +x /tmp/wine_test.sh
    bash /tmp/wine_test.sh || log_warning "Basic Wine test failed"
    
    # Clean up
    rm -rf /tmp/wine_test_prefix /tmp/wine_test.sh 2>/dev/null
    
    echo
}

check_steam_library() {
    log_info "=== Steam Library Check ==="
    
    # Look for game in various locations
    local found_game=false
    local search_paths=(
        "$HOME/.steam/steam/steamapps"
        "$HOME/.local/share/Steam/steamapps"
        "/mnt/*/games/steam/steamapps"
        "/mnt/*/Games/Steam/steamapps"
        "/mnt/*/*/steamapps"
    )
    
    for search_path in "${search_paths[@]}"; do
        local game_paths=$(find $search_path -name "*Ready*" -type d 2>/dev/null || true)
        if [ -n "$game_paths" ]; then
            log_success "Found game at: $game_paths"
            found_game=true
            
            # Check game executable
            local game_dir="$game_paths"
            if [ -f "$game_dir/ReadyOrNot.exe" ]; then
                log_success "Game executable found"
                log_info "Game size: $(du -sh "$game_dir" 2>/dev/null | cut -f1)"
            else
                log_warning "Game executable not found in $game_dir"
            fi
        fi
    done
    
    if ! $found_game; then
        log_error "Ready or Not installation not found!"
        log_info "Please verify the game is installed through Steam"
    fi
    
    echo
}

analyze_crash_patterns() {
    log_info "=== Crash Pattern Analysis ==="
    
    # Check for common crash causes
    log_info "Checking for common Ready or Not crash patterns:"
    
    # Check system resources
    local memory_mb=$(free -m | awk 'NR==2{printf "%.0f", $7}')
    if [ "$memory_mb" -lt 4000 ]; then
        log_warning "Low available memory: ${memory_mb}MB (need 4GB+)"
    else
        log_success "Available memory: ${memory_mb}MB"
    fi
    
    # Check disk space
    local disk_space=$(df -h ~ | awk 'NR==2 {print $4}')
    log_info "Available disk space: $disk_space"
    
    # Check for conflicting processes
    local conflicting_procs=$(pgrep -f "eac|battleye|vanguard" || true)
    if [ -n "$conflicting_procs" ]; then
        log_warning "Conflicting anti-cheat processes found: $conflicting_procs"
    fi
    
    echo
}

suggest_alternative_approaches() {
    log_info "=== Alternative Troubleshooting Approaches ==="
    
    echo "1. Try without Steam Tinker Launch:"
    echo "   - Set compatibility tool to 'Proton Experimental'"
    echo "   - Add launch options: PROTON_USE_WINED3D=1 %command% -noeac -dx11"
    echo
    echo "2. Test with different Proton versions:"
    echo "   - Proton 8.0-5 (stable)"
    echo "   - Proton 7.0-6 (older, more compatible)"
    echo "   - GE-Proton8-32 (community build)"
    echo
    echo "3. Try Lutris instead of Steam:"
    echo "   - Install Lutris"
    echo "   - Use Lutris Wine runners"
    echo "   - More granular control over Wine settings"
    echo
    echo "4. Verify game files:"
    echo "   - Steam → Ready or Not → Properties → Local Files → Verify integrity"
    echo
    echo "5. Check for Windows dependencies:"
    echo "   - Install Visual C++ Redistributables via Winetricks"
    echo "   - Install DirectX runtime"
    echo
    echo "6. Hardware-specific issues:"
    echo "   - Try different display outputs"
    echo "   - Test with integrated graphics (if available)"
    echo "   - Check for BIOS/UEFI settings affecting compatibility"
    echo
}

create_manual_test_script() {
    log_info "=== Creating Manual Test Script ==="
    
    cat > /tmp/manual_ready_or_not_test.sh << 'EOF'
#!/bin/bash

# Manual Ready or Not Test Script
# Run this to test the game with minimal environment

export STEAM_COMPAT_DATA_PATH="$HOME/.steam/steam/steamapps/compatdata/1144200"
export STEAM_COMPAT_CLIENT_INSTALL_PATH="$HOME/.steam/steam"
export PROTON_LOG=1
export PROTON_LOG_DIR="/tmp/proton_test_logs"
export WINEDEBUG="+dll,+module,+registry"

# Create log directory
mkdir -p /tmp/proton_test_logs

# Find the game executable
GAME_EXE=""
for path in "$HOME/.steam/steam/steamapps/common/Ready Or Not" \
           "$HOME/.local/share/Steam/steamapps/common/Ready Or Not" \
           "/mnt/*/games/steam/steamapps/common/Ready Or Not" \
           "/mnt/*/Games/Steam/steamapps/common/Ready Or Not"; do
    if [ -f "$path/ReadyOrNot.exe" ]; then
        GAME_EXE="$path/ReadyOrNot.exe"
        break
    fi
done

if [ -z "$GAME_EXE" ]; then
    echo "ERROR: Ready or Not executable not found!"
    exit 1
fi

echo "Found game: $GAME_EXE"
echo "Starting manual test..."

# Try to run the game directly with Proton
timeout 30s ~/.steam/steam/steamapps/common/Proton\ -\ Experimental/proton run "$GAME_EXE" -noeac -dx11

echo "Test completed. Check logs in /tmp/proton_test_logs/"
EOF
    
    chmod +x /tmp/manual_ready_or_not_test.sh
    log_success "Manual test script created: /tmp/manual_ready_or_not_test.sh"
    echo
}

main() {
    log_info "Starting comprehensive crash diagnosis..."
    echo
    
    check_system_prerequisites
    check_proton_versions
    test_basic_compatibility
    check_steam_library
    analyze_crash_patterns
    suggest_alternative_approaches
    create_manual_test_script
    
    log_info "=== Summary ==="
    log_info "Crash diagnosis complete. Try the suggested approaches above."
    log_info "If all else fails, the game may have compatibility issues with your specific system configuration."
}

main "$@"