#!/bin/bash

# Ready or Not Crash Fix Script
# Fixes common crash issues with splash screen crashes

set -e

GAME_ID="1144200"
STL_CONFIG_DIR="$HOME/.config/steamtinkerlaunch"
GAME_CONFIG="$STL_CONFIG_DIR/gamecfgs/$GAME_ID.conf"

# 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"; }

backup_config() {
    if [ -f "$GAME_CONFIG" ]; then
        local backup="$GAME_CONFIG.crash-fix-backup.$(date +%Y%m%d_%H%M%S)"
        cp "$GAME_CONFIG" "$backup"
        log_success "Config backed up to: $backup"
    fi
}

create_minimal_config() {
    log_info "Creating minimal crash-resistant configuration..."
    
    cat > "$GAME_CONFIG" << 'EOF'
## config Version: v12.12 - MINIMAL CRASH FIX
##########################
#GAMENAME="Ready Or Not"
#GAMEEXE="ReadyOrNot.exe"  
#GAMEID="1144200"
##########################

# Essential settings only
KEEPSTLOPEN="0"
USESLR="1"
FORCESLR="0"
USEREAP="1"
FORCEREAP="0"

# Proton settings - using stable version
USEPROTON="GE-Proton9-11"
REDIRCOMPDATA="disabled"
REDIRSTEAMUSER="disabled"
AUTOBUMPGE="0"
AUTOBUMPPROTON="0"

# Game arguments - minimal for crash fix
GAMEARGS="-noeac"
HARDARGS="nope"

# Performance tools - disabled for crash testing
USEGAMEMODERUN="0"
USEGAMESCOPE="0"
GAMESCOPE_ARGS="none"
USEMANGOHUD="0"
USEMANGOAPP="0"

# Audio - basic settings
CHANGE_PULSE_LATENCY="1"
STL_PULSE_LATENCY_MSEC="120"

# Basic Wine/Proton settings
USEWINE="0"
VIRTUALDESKTOP="0"
VDRES="none"

# DXVK - disabled for crash testing
USE_STLDXVKCFG="0"
DXVK_HUD="0"
DXVK_LOG_LEVEL="none"
DXVK_LOG_PATH="none"
DXVK_ASYNC="0"
DXVK_HDR="0"

# Proton crash prevention
PROTON_USE_WINED3D="1"
PROTON_NO_D3D11="0"
PROTON_NO_D3D10="0"
PROTON_NO_ESYNC="0"
PROTON_NO_FSYNC="0"
PROTON_FORCE_LARGE_ADDRESS_AWARE="1"
PROTON_LOG="1"
PROTON_LOG_DIR="STLCFGDIR/logs/proton/id"

# NVIDIA settings - basic only
PROTON_ENABLE_NVAPI="0"
PROTON_HIDE_NVIDIA_GPU="1"
USEDLSS="0"

# Cleanup and debugging
CLEANPROTONTEMP="1"
CRASHGUESS="5"
STLWINEDEBUG="-all"

# Disable all extras that could cause crashes
USECUSTOMCMD="0"
USEIGCS="0"
UUUSEIGCS="0"
UUUSEPATCH="0"
UUUSEVR="0"
USEOBSCAP="0"
USEZINK="0"
USEPRIMERUN="0"
TOGSTEAMWEBHELPER="0"
ENABLE_VKBASALT="0"
RUN_NYRNA="0"
RUN_REPLAY="0"
RUN_X64DBG="0"
RUN_GDB="0"
USE_WDIB="0"
USEVORTEX="0"
RUN_WINETRICKS="0"
USEGEOELF="0"
INSTALL_RESHADE="0"
USERESHADE="0"
USEOPENVRFSR="0"
RUNSBSVR="0"
REGEDIT="0"
WAITEDITOR="0"
STEAMAPPIDFILE="0"
CHECKCOLLECTIONS="1"
BACKUPSTEAMUSER="0"
RESTORESTEAMUSER="none"
USESUSYM="0"
USEGLOBSUSYM="0"
STRACERUN="0"
USENETMON="0"
BLOCKINTERNET="0"
USEWINEDEBUGPROTON="0"
PROTON_DUMP_DEBUG_COMMANDS="0"
ENABLE_WINESYNC="0"
USERAYTRACING="0"
WINE_FULLSCREEN_INTEGER_SCALING="0"
WINE_FULLSCREEN_FSR="0"
WINE_FULLSCREEN_FSR_STRENGTH="2"
STLWINEDLLOVERRIDES="none"
WINE_LOG_DIR="STLCFGDIR/logs/wine"
USERSTART="none"
USERSTOP="none"
AUTOCONTY="0"
USECONTY="0"
ONLYWICO="0"
GAMESCREENRES="none"
HELPURL="none"
CREATEDESKTOPICON="0"
FIXSYMLINKS="0"
UNSYMLINK="0"
DELPFX="0"
RUN_DEPS="0"
SORTGARGS="0"
WAITMO2="0"
MO2MODE="disabled"
USESPECIALK="0"
SDLUSEWAYLAND="0"
STLRAD_PFTST="none"
SPEKVERS="default"
AUTOSPEK="0"
USEFWS="0"
USEPEV_PELDD="0"
USEPEV_PEPACK="0"
USEPEV_PERES="0"
USEPEV_PESCAN="0"
USEPEV_PESEC="0"
USEPEV_PESTR="0"
USEPEV_READPE="0"
STL_VKD3D_CONFIG="none"
STL_VKD3D_DEBUG="none"
STL_VKD3D_SHADER_DEBUG="none"
STL_VKD3D_LOG_FILE="none"
STL_VKD3D_VULKAN_DEVICE="none"
STL_VKD3D_FILTER_DEVICE_NAME="none"
STL_VKD3D_DISABLE_EXTENSIONS="none"
STL_VKD3D_TEST_DEBUG="0"
STL_VKD3D_TEST_FILTER="none"
STL_VKD3D_TEST_EXCLUDE="none"
STL_VKD3D_TEST_PLATFORM="none"
STL_VKD3D_TEST_BUG="none"
STL_VKD3D_PROFILE_PATH="none"
SLOARGS="none"
ASKCNT="0"
EOF

    log_success "Minimal configuration created"
}

clean_old_data() {
    log_info "Cleaning old game data that might cause crashes..."
    
    # Remove old compatdata
    local compatdata_paths=(
        "$HOME/.steam/steam/steamapps/compatdata/$GAME_ID"
        "$HOME/.local/share/Steam/steamapps/compatdata/$GAME_ID"
    )
    
    for path in "${compatdata_paths[@]}"; do
        if [ -d "$path" ]; then
            log_info "Removing old compatdata: $path"
            rm -rf "$path"
        fi
    done
    
    # Clean DXVK cache
    if [ -d "/tmp/dxvk-cache" ]; then
        log_info "Cleaning DXVK cache"
        rm -rf /tmp/dxvk-cache/*
    fi
    
    log_success "Old data cleaned"
}

create_debug_launch_script() {
    log_info "Creating debug launch script..."
    
    cat > "$HOME/.local/bin/launch-ready-or-not-debug" << 'EOF'
#!/bin/bash

# Ready or Not Debug Launch Script
# Use this to get detailed crash information

export PROTON_LOG=1
export PROTON_LOG_DIR="$HOME/.config/steamtinkerlaunch/logs/proton/debug"
export WINEDEBUG="+dll,+module"

# Create log directory
mkdir -p "$HOME/.config/steamtinkerlaunch/logs/proton/debug"

echo "Launching Ready or Not in debug mode..."
echo "Logs will be in: $HOME/.config/steamtinkerlaunch/logs/proton/debug"

# Launch game
steam steam://rungameid/1144200

echo "Check logs for crash details:"
echo "Main log: $HOME/.config/steamtinkerlaunch/logs/proton/debug/steam-1144200.log"
EOF
    
    chmod +x "$HOME/.local/bin/launch-ready-or-not-debug"
    log_success "Debug launcher created: ~/.local/bin/launch-ready-or-not-debug"
}

show_next_steps() {
    echo
    log_success "Crash fix applied!"
    echo
    log_info "Next Steps:"
    echo "1. Launch Ready or Not through Steam"
    echo "2. If it still crashes, use debug launcher:"
    echo "   ~/.local/bin/launch-ready-or-not-debug"
    echo "3. Check debug logs in ~/.config/steamtinkerlaunch/logs/"
    echo "4. If it works, gradually re-enable features:"
    echo "   - Enable DXVK: PROTON_USE_WINED3D=\"0\", DXVK_ASYNC=\"1\""
    echo "   - Enable GameScope: USEGAMESCOPE=\"1\""
    echo "   - Enable NVIDIA features: PROTON_ENABLE_NVAPI=\"1\""
    echo
    log_warning "Current config uses WineD3D for stability"
    log_warning "Performance will be lower but game should run"
}

main() {
    log_info "Fixing Ready or Not splash screen crash..."
    echo
    
    backup_config
    clean_old_data
    create_minimal_config
    create_debug_launch_script
    show_next_steps
}

main "$@"