#!/bin/bash

# Ready or Not Steam Tinker Launch Setup Script
# Optimized for NVIDIA GPUs and 1440p gaming on 4K monitors

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
STL_CONFIG_DIR="$HOME/.config/steamtinkerlaunch"
GAME_CONFIG_DIR="$STL_CONFIG_DIR/gamecfgs"
GAME_ID="1144200"

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

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_dependencies() {
    log_info "Checking dependencies..."
    
    # Check if Steam Tinker Launch is installed
    if ! command -v steamtinkerlaunch >/dev/null 2>&1; then
        log_error "Steam Tinker Launch is not installed!"
        log_info "Please install it first: https://github.com/frostworx/steamtinkerlaunch"
        exit 1
    fi
    
    # Check if GameScope is available
    if ! command -v gamescope >/dev/null 2>&1; then
        log_warning "GameScope not found. GameScope is recommended for optimal 1440p gaming on 4K monitors."
        log_info "Install with: sudo pacman -S gamescope (Arch) or sudo apt install gamescope (Ubuntu)"
    fi
    
    # Check NVIDIA drivers
    if ! command -v nvidia-smi >/dev/null 2>&1; then
        log_error "NVIDIA drivers not found!"
        log_info "Please install NVIDIA drivers first"
        exit 1
    fi
    
    log_success "Dependencies check completed"
}

backup_existing_config() {
    if [ -f "$GAME_CONFIG_DIR/$GAME_ID.conf" ]; then
        log_info "Backing up existing configuration..."
        cp "$GAME_CONFIG_DIR/$GAME_ID.conf" "$GAME_CONFIG_DIR/$GAME_ID.conf.backup.$(date +%Y%m%d_%H%M%S)"
        log_success "Backup created"
    fi
}

setup_directories() {
    log_info "Setting up Steam Tinker Launch directories..."
    
    mkdir -p "$STL_CONFIG_DIR"
    mkdir -p "$GAME_CONFIG_DIR"
    mkdir -p "$STL_CONFIG_DIR/dxvk"
    mkdir -p "$STL_CONFIG_DIR/logs"
    
    log_success "Directories created"
}

install_game_config() {
    log_info "Installing Ready or Not configuration..."
    
    if [ ! -f "$SCRIPT_DIR/1144200-nvidia-1440p.conf" ]; then
        log_error "Configuration file not found: $SCRIPT_DIR/1144200-nvidia-1440p.conf"
        exit 1
    fi
    
    cp "$SCRIPT_DIR/1144200-nvidia-1440p.conf" "$GAME_CONFIG_DIR/$GAME_ID.conf"
    chmod 644 "$GAME_CONFIG_DIR/$GAME_ID.conf"
    
    log_success "Game configuration installed"
}

create_dxvk_config() {
    log_info "Creating DXVK configuration..."
    
    cat > "$STL_CONFIG_DIR/dxvk/$GAME_ID.conf" << 'EOF'
# DXVK configuration for Ready or Not (NVIDIA optimized)

# Reduce input latency
dxgi.maxFrameLatency = 1
d3d9.maxFrameLatency = 1

# NVIDIA-specific optimizations
dxgi.nvapiHack = True

# Memory management for NVIDIA GPUs
dxgi.maxDeviceMemory = 8192
dxgi.maxSharedMemory = 1024

# Enable async shader compilation
dxvk.enableAsync = True

# HDR support
dxgi.enableHDR = True

# Disable tear-free for better performance
dxgi.tearFree = False

# Sync interval (0 = unlimited, 1 = vsync)
d3d9.presentInterval = 0
EOF
    
    log_success "DXVK configuration created"
}

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

# Ready or Not Launch Helper
# Optimized for NVIDIA + 1440p gaming

# Source NVIDIA environment variables
export __NV_PRIME_RENDER_OFFLOAD=1
export __GLX_VENDOR_LIBRARY_NAME=nvidia
export PROTON_SET_GAME_DRIVE=1
export PULSE_LATENCY_MSEC=60
export PIPEWIRE_LATENCY=128/48000
export VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/nvidia_icd.json
export DXVK_ASYNC=1
export DXVK_HDR=1
export PROTON_ENABLE_NVAPI=1
export PROTON_HIDE_NVIDIA_GPU=0
export PROTON_FORCE_LARGE_ADDRESS_AWARE=1

# Launch the game
exec steam steam://rungameid/1144200
EOF
    
    chmod +x "$HOME/.local/bin/launch-ready-or-not"
    
    log_success "Launch helper script created at ~/.local/bin/launch-ready-or-not"
}

test_configuration() {
    log_info "Testing configuration..."
    
    # Check if game config exists and is readable
    if [ -r "$GAME_CONFIG_DIR/$GAME_ID.conf" ]; then
        log_success "Game configuration is readable"
    else
        log_error "Game configuration is not readable"
        exit 1
    fi
    
    # Check if DXVK config exists
    if [ -r "$STL_CONFIG_DIR/dxvk/$GAME_ID.conf" ]; then
        log_success "DXVK configuration is readable"
    else
        log_warning "DXVK configuration not found"
    fi
    
    log_success "Configuration test completed"
}

show_next_steps() {
    echo
    log_success "Setup completed successfully!"
    echo
    log_info "Next steps:"
    echo "1. Launch Steam and go to Ready or Not properties"
    echo "2. In Launch Options, you can optionally add: %command%"
    echo "3. Launch the game - Steam Tinker Launch should automatically detect and use the configuration"
    echo "4. For troubleshooting, check ~/.config/steamtinkerlaunch/logs/"
    echo
    log_info "Performance tips:"
    echo "- The game is configured for 1440p gaming with DLSS enabled"
    echo "- GameScope will handle scaling to your 4K monitor"
    echo "- Use the launch helper: ~/.local/bin/launch-ready-or-not"
    echo "- Monitor performance with the built-in MangoHUD overlay"
    echo
    log_info "If you experience issues:"
    echo "- Check the troubleshooting guide in this directory"
    echo "- Disable GameScope temporarily if needed"
    echo "- Try different Proton versions in Steam"
}

main() {
    log_info "Setting up Ready or Not for Steam Tinker Launch..."
    log_info "Target: NVIDIA GPU, 1440p gaming on 4K monitor"
    echo
    
    check_dependencies
    setup_directories
    backup_existing_config
    install_game_config
    create_dxvk_config
    create_launch_script
    test_configuration
    show_next_steps
}

main "$@"