#!/bin/bash

# Steam Tinker Launch Log Checker
# Analyzes recent STL logs for common issues

set -e

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

STL_LOG_DIR="$HOME/.config/steamtinkerlaunch/logs"
GAME_ID="1144200"

check_stl_logs() {
    log_info "Checking Steam Tinker Launch logs..."
    
    if [ ! -d "$STL_LOG_DIR" ]; then
        log_error "STL logs directory not found: $STL_LOG_DIR"
        return 1
    fi
    
    # Check main STL log
    local main_log="$STL_LOG_DIR/steamtinkerlaunch.log"
    if [ -f "$main_log" ]; then
        log_info "Recent STL activity (last 20 lines):"
        echo "----------------------------------------"
        tail -20 "$main_log" | while read line; do
            if echo "$line" | grep -qi "error\|fail\|crash\|exception"; then
                echo -e "${RED}$line${NC}"
            elif echo "$line" | grep -qi "warning"; then
                echo -e "${YELLOW}$line${NC}"
            else
                echo "$line"
            fi
        done
        echo "----------------------------------------"
    else
        log_warning "Main STL log not found"
    fi
    
    # Check for game-specific logs
    local proton_log_dir="$STL_LOG_DIR/proton/id"
    if [ -d "$proton_log_dir" ]; then
        log_info "Checking Proton logs..."
        ls -la "$proton_log_dir" 2>/dev/null || log_warning "No Proton logs found"
    fi
    
    # Check for wine logs
    local wine_log_dir="$STL_LOG_DIR/wine"
    if [ -d "$wine_log_dir" ]; then
        log_info "Checking Wine logs..."
        ls -la "$wine_log_dir" 2>/dev/null || log_warning "No Wine logs found"
    fi
    
    # Check for DXVK logs
    local dxvk_log_dir="$STL_LOG_DIR/dxvk"
    if [ -d "$dxvk_log_dir" ]; then
        log_info "Checking DXVK logs..."
        ls -la "$dxvk_log_dir" 2>/dev/null || log_warning "No DXVK logs found"
    fi
}

check_proton_prefix() {
    log_info "Checking Proton prefix status..."
    
    local compatdata_dirs=(
        "$HOME/.steam/steam/steamapps/compatdata/$GAME_ID"
        "$HOME/.local/share/Steam/steamapps/compatdata/$GAME_ID"
    )
    
    for compatdata in "${compatdata_dirs[@]}"; do
        if [ -d "$compatdata" ]; then
            log_success "Found compatdata: $compatdata"
            log_info "Prefix size: $(du -sh "$compatdata" 2>/dev/null | cut -f1)"
            
            # Check for common crash indicators
            if [ -f "$compatdata/pfx/drive_c/users/steamuser/Temp/steam_appid.txt" ]; then
                local appid=$(cat "$compatdata/pfx/drive_c/users/steamuser/Temp/steam_appid.txt" 2>/dev/null)
                log_info "Steam App ID in prefix: $appid"
            fi
            
            # Check prefix health
            if [ -f "$compatdata/pfx/system.reg" ]; then
                log_success "Wine prefix appears healthy"
            else
                log_warning "Wine prefix may be corrupted"
            fi
            
            return 0
        fi
    done
    
    log_warning "No compatdata found - this might be the issue"
}

analyze_common_crashes() {
    log_info "Analyzing for common Ready or Not crash patterns..."
    
    local main_log="$STL_LOG_DIR/steamtinkerlaunch.log"
    if [ -f "$main_log" ]; then
        # Check for EasyAntiCheat issues
        if grep -qi "easyanticheat\|eac" "$main_log"; then
            log_warning "EasyAntiCheat detected in logs - this can cause crashes"
            log_info "Solution: Ensure -noeac is in game arguments"
        fi
        
        # Check for DirectX issues
        if grep -qi "d3d\|directx\|dxgi" "$main_log"; then
            log_warning "DirectX/DXVK issues detected"
            log_info "Solution: Try PROTON_USE_WINED3D=1 or different Proton version"
        fi
        
        # Check for memory issues
        if grep -qi "memory\|allocation\|heap" "$main_log"; then
            log_warning "Memory issues detected"
            log_info "Solution: Ensure PROTON_FORCE_LARGE_ADDRESS_AWARE=1 is set"
        fi
        
        # Check for Vulkan issues
        if grep -qi "vulkan\|vk_" "$main_log"; then
            log_warning "Vulkan issues detected"
            log_info "Solution: Verify NVIDIA drivers and Vulkan support"
        fi
    fi
}

suggest_fixes() {
    echo
    log_info "=== Common Fixes for Ready or Not Crashes ==="
    echo
    echo "1. Reset Proton Prefix:"
    echo "   rm -rf ~/.steam/steam/steamapps/compatdata/1144200/"
    echo "   (Steam will recreate on next launch)"
    echo
    echo "2. Try Different Proton Version:"
    echo "   - GE-Proton9-11 (older, more stable)"
    echo "   - Proton 8.0-5 (Steam's stable version)"
    echo
    echo "3. Disable GameScope temporarily:"
    echo "   Edit config: USEGAMESCOPE=\"0\""
    echo
    echo "4. Enable Wine debug for more info:"
    echo "   Edit config: PROTON_LOG=\"1\""
    echo
    echo "5. Try minimal STL settings:"
    echo "   - Disable all extras except basic Proton"
    echo "   - Only keep: GAMEARGS=\"-noeac\""
    echo
    echo "6. Fallback to WineD3D:"
    echo "   Edit config: PROTON_USE_WINED3D=\"1\""
}

main() {
    log_info "Analyzing Ready or Not crash..."
    echo
    
    check_stl_logs
    echo
    check_proton_prefix  
    echo
    analyze_common_crashes
    
    suggest_fixes
}

main "$@"