#!/bin/bash

# Gaming Setup Validation Script
# Validates gaming environment and dependencies

set -e

# Colors for output
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_nvidia_setup() {
    log_info "Checking NVIDIA setup..."
    
    if command -v nvidia-smi >/dev/null 2>&1; then
        log_success "NVIDIA drivers installed"
        nvidia-smi --query-gpu=name,memory.total --format=csv,noheader,nounits | head -1
    else
        log_error "NVIDIA drivers not found"
        return 1
    fi
    
    if command -v vulkaninfo >/dev/null 2>&1; then
        local gpu_name=$(vulkaninfo | grep "deviceName" | head -1 | cut -d'"' -f2)
        if echo "$gpu_name" | grep -qi nvidia; then
            log_success "Vulkan NVIDIA support: $gpu_name"
        else
            log_warning "Vulkan may not be using NVIDIA GPU: $gpu_name"
        fi
    else
        log_warning "vulkaninfo not available - install vulkan-tools"
    fi
}

check_steam_setup() {
    log_info "Checking Steam setup..."
    
    if command -v steam >/dev/null 2>&1; then
        log_success "Steam installed"
    else
        log_error "Steam not found"
        return 1
    fi
    
    if command -v steamtinkerlaunch >/dev/null 2>&1; then
        local stl_version=$(steamtinkerlaunch --version 2>/dev/null || echo "unknown")
        log_success "Steam Tinker Launch installed: $stl_version"
    else
        log_error "Steam Tinker Launch not found"
        return 1
    fi
}

check_gamescope() {
    log_info "Checking GameScope..."
    
    if command -v gamescope >/dev/null 2>&1; then
        local gs_version=$(gamescope --version 2>&1 | head -1 || echo "unknown")
        log_success "GameScope installed: $gs_version"
    else
        log_warning "GameScope not found - recommended for 4K monitor scaling"
    fi
}

check_audio_setup() {
    log_info "Checking audio setup..."
    
    if command -v pipewire >/dev/null 2>&1 || pgrep -x pipewire >/dev/null; then
        log_success "PipeWire detected"
    elif command -v pulseaudio >/dev/null 2>&1 || pgrep -x pulseaudio >/dev/null; then
        log_success "PulseAudio detected"
    else
        log_warning "No audio system detected"
    fi
}

check_display_setup() {
    log_info "Checking display setup..."
    
    if command -v xrandr >/dev/null 2>&1; then
        local primary_display=$(xrandr | grep " connected primary" | head -1)
        log_info "Primary display: $primary_display"
        
        if echo "$primary_display" | grep -q "3840x2160"; then
            log_success "4K monitor detected"
        elif echo "$primary_display" | grep -q "2560x1440"; then
            log_success "1440p monitor detected"
        else
            log_info "Display resolution: $(echo $primary_display | grep -o '[0-9]*x[0-9]*')"
        fi
    else
        log_warning "Cannot detect display information (xrandr not available)"
    fi
}

check_ready_or_not_config() {
    log_info "Checking Ready or Not configuration..."
    
    local config_file="$HOME/.config/steamtinkerlaunch/gamecfgs/1144200.conf"
    local dxvk_config="$HOME/.config/steamtinkerlaunch/dxvk/1144200.conf"
    
    if [ -f "$config_file" ]; then
        log_success "Ready or Not STL config found"
        
        # Check for key NVIDIA settings
        if grep -q "PROTON_ENABLE_NVAPI=\"1\"" "$config_file"; then
            log_success "NVAPI enabled for DLSS support"
        else
            log_warning "NVAPI not enabled - DLSS may not work"
        fi
        
        if grep -q "USEGAMESCOPE=\"1\"" "$config_file"; then
            log_success "GameScope enabled for display scaling"
        else
            log_info "GameScope disabled in config"
        fi
    else
        log_error "Ready or Not STL config not found"
        log_info "Run: /mnt/NV2/Development/claude-home/gaming/examples/ready-or-not/setup-ready-or-not.sh"
        return 1
    fi
    
    if [ -f "$dxvk_config" ]; then
        log_success "DXVK config found"
    else
        log_warning "DXVK config not found - may impact performance"
    fi
}

check_steam_library() {
    log_info "Checking for Ready or Not in Steam library..."
    
    # Common Steam library locations
    local steam_dirs=(
        "$HOME/.steam/steam/steamapps"
        "$HOME/.local/share/Steam/steamapps" 
        "/mnt/*/games/steam/steamapps"
        "/mnt/*/Games/Steam/steamapps"
    )
    
    local found=false
    for steam_dir in "${steam_dirs[@]}"; do
        if [ -d "$steam_dir/common/Ready Or Not" ]; then
            log_success "Ready or Not found: $steam_dir/common/Ready Or Not"
            found=true
            break
        fi
    done
    
    if ! $found; then
        log_warning "Ready or Not not found in Steam library"
        log_info "Make sure the game is installed through Steam"
    fi
}

check_performance_tools() {
    log_info "Checking performance monitoring tools..."
    
    if command -v mangohud >/dev/null 2>&1; then
        log_success "MangoHUD available for performance monitoring"
    else
        log_warning "MangoHUD not found - install for performance overlay"
    fi
    
    if command -v gamemode >/dev/null 2>&1 || [ -f "/usr/lib/libgamemode.so" ]; then
        log_success "GameMode available for CPU optimization"
    else
        log_warning "GameMode not found - install for CPU performance boost"
    fi
}

show_summary() {
    echo
    log_info "=== Validation Summary ==="
    echo "If all checks passed, you should be ready to game!"
    echo
    log_info "To launch Ready or Not:"
    echo "1. Use helper script: ~/.local/bin/launch-ready-or-not"
    echo "2. Or launch through Steam (STL will auto-configure)"
    echo
    log_info "For troubleshooting:"
    echo "- Check logs: ~/.config/steamtinkerlaunch/logs/"
    echo "- Read guide: /mnt/NV2/Development/claude-home/gaming/troubleshooting.md"
    echo "- Monitor performance: Enable MangoHUD overlay in-game"
}

main() {
    log_info "Validating gaming setup for Ready or Not..."
    log_info "Target: NVIDIA GPU + Steam Tinker Launch + 1440p gaming"
    echo
    
    local errors=0
    
    check_nvidia_setup || ((errors++))
    echo
    check_steam_setup || ((errors++))
    echo
    check_gamescope
    echo
    check_audio_setup
    echo
    check_display_setup
    echo
    check_ready_or_not_config || ((errors++))
    echo
    check_steam_library
    echo
    check_performance_tools
    
    if [ $errors -eq 0 ]; then
        echo
        log_success "All critical checks passed! Gaming setup looks good."
    else
        echo
        log_warning "$errors critical issues found. Please address them before gaming."
    fi
    
    show_summary
}

main "$@"