@echo off
setlocal EnableExtensions

set "APPDIR=%~dp0"
set "APPDIR=%APPDIR:~0,-1%"
set "EXE=%APPDIR%\ChampionsKOFEmulator.exe"
set "LOGROOT=%APPDIR%\_runtime_debug"
set "LOGDIR=%LOGROOT%\logs"
set "CONFIGDIR=%LOGROOT%\config"
set "REPORT=%USERPROFILE%\Desktop\ChampionsKOF_diagnostico.txt"

if not exist "%EXE%" (
  echo Este arquivo precisa ficar dentro da pasta ChampionsKOF, ao lado de ChampionsKOFEmulator.exe.
  echo.
  echo Pasta atual: %APPDIR%
  pause
  exit /b 1
)

taskkill /IM ChampionsKOFEmulator.exe /F >nul 2>nul
taskkill /IM ChampionsKOFUpdater.exe /F >nul 2>nul

if exist "%APPDIR%\.update-staging" rmdir /S /Q "%APPDIR%\.update-staging" >nul 2>nul
if exist "%LOGROOT%" rmdir /S /Q "%LOGROOT%" >nul 2>nul
mkdir "%LOGDIR%" >nul 2>nul
mkdir "%CONFIGDIR%" >nul 2>nul

reg delete "HKCU\Software\ChampionsKOF\Emulator" /f >nul 2>nul

set "QT_OPENGL=software"
set "QT_QUICK_BACKEND=software"
set "QSG_RHI_BACKEND=software"
set "QT_WIDGETS_RHI=0"
set "QT_ENABLE_HIGHDPI_SCALING=0"
set "QT_SCALE_FACTOR=1"
set "QT_AUTO_SCREEN_SCALE_FACTOR=0"
set "QT_QPA_PLATFORM_PLUGIN_PATH=%APPDIR%\platforms"
set "PATH=%APPDIR%;%APPDIR%\platforms;%PATH%"

echo ChampionsKOF diagnostico > "%REPORT%"
echo Data: %DATE% %TIME% >> "%REPORT%"
echo Pasta: %APPDIR% >> "%REPORT%"
echo. >> "%REPORT%"
echo Arquivos principais: >> "%REPORT%"
dir "%APPDIR%\ChampionsKOFEmulator.exe" "%APPDIR%\Qt6Core.dll" "%APPDIR%\Qt6Gui.dll" "%APPDIR%\Qt6Widgets.dll" "%APPDIR%\platforms\qwindows.dll" >> "%REPORT%" 2>&1
echo. >> "%REPORT%"

cd /d "%APPDIR%"
start "" "%EXE%" --skip-update --config-dir "%CONFIGDIR%" --log-dir "%LOGDIR%"

timeout /t 8 /nobreak >nul

powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$p = Get-Process ChampionsKOFEmulator -ErrorAction SilentlyContinue; " ^
  "'Processo:' | Out-File -Append '%REPORT%'; " ^
  "if ($p) { $p | Select-Object Id,ProcessName,MainWindowTitle,Responding,StartTime,Path | Format-List | Out-File -Append '%REPORT%' } else { 'Nao ha processo ChampionsKOFEmulator rodando.' | Out-File -Append '%REPORT%' }; " ^
  "'Logs:' | Out-File -Append '%REPORT%'; " ^
  "Get-ChildItem '%LOGDIR%' -Force -ErrorAction SilentlyContinue | Select-Object FullName,Length,LastWriteTime | Format-List | Out-File -Append '%REPORT%'; " ^
  "'Erros recentes do Windows:' | Out-File -Append '%REPORT%'; " ^
  "Get-WinEvent -FilterHashtable @{LogName='Application'; StartTime=(Get-Date).AddMinutes(-15)} -ErrorAction SilentlyContinue | Where-Object { $_.ProviderName -in @('Application Error','Windows Error Reporting') -or $_.Message -like '*ChampionsKOF*' -or $_.Message -like '*Qt6*' } | Select-Object TimeCreated,ProviderName,Id,Message -First 8 | Format-List | Out-File -Append '%REPORT%';"

start notepad "%REPORT%"
exit /b 0
