@echo off
setlocal
chcp 65001 >nul
cd /d "%~dp0"
set "PYTHONUTF8=1"
set "PYTHONIOENCODING=utf-8"

set "PYTHON_CMD="
where py >nul 2>nul && set "PYTHON_CMD=py -3"
if not defined PYTHON_CMD (
    where python >nul 2>nul && set "PYTHON_CMD=python"
)

if not defined PYTHON_CMD (
    echo [ERROR] Python 3 was not found.
    echo Install Python 3 and make sure py or python is available in PATH.
    pause
    exit /b 1
)

if not exist "RestoreGameAssets.py" (
    echo [ERROR] RestoreGameAssets.py was not found in the current folder.
    pause
    exit /b 1
)

if not exist "bin\astcenc-avx2.exe" (
    echo [WARN] bin\astcenc-avx2.exe was not found.
    echo [WARN] ASTC images will fall back to .astc output unless you select another astcenc in the GUI.
)

set "TARGET_PATH="
set "FORCE_CLI="

if /I "%~1"=="--cli" shift & set "FORCE_CLI=1"
set "TARGET_PATH=%~1"

if defined FORCE_CLI goto run_cli
if defined RESTORE_FORCE_CLI goto run_cli

%PYTHON_CMD% -c "import PyQt5" >nul 2>nul
if "%ERRORLEVEL%"=="0" goto run_gui

echo [WARN] PyQt5 was not found. Falling back to CLI mode.
echo [WARN] Install with: pip install PyQt5
echo.
goto run_cli

:run_gui
if not exist "RestoreGameAssetsGUI.py" (
    echo [ERROR] RestoreGameAssetsGUI.py was not found in the current folder.
    call :maybe_pause
    exit /b 1
)
echo [INFO] Starting Qt5 GUI...
if defined TARGET_PATH (
    call %PYTHON_CMD% RestoreGameAssetsGUI.py "%TARGET_PATH%"
) else (
    call %PYTHON_CMD% RestoreGameAssetsGUI.py
)
set "EXIT_CODE=%ERRORLEVEL%"
goto finish

:run_cli
if defined TARGET_PATH set "RESTORE_ROOT=%TARGET_PATH%"
echo [INFO] Starting CLI restore into pack\restored ...
echo.
call %PYTHON_CMD% RestoreGameAssets.py
set "EXIT_CODE=%ERRORLEVEL%"

:finish
echo.
if not "%EXIT_CODE%"=="0" (
    echo [ERROR] Restore failed. Exit code: %EXIT_CODE%
    call :maybe_pause
    exit /b %EXIT_CODE%
)

echo [DONE] Restore tool exited normally.
echo [DONE] Default output: pack\restored
echo [DONE] Default backups: pack\restored\_partial_backups
call :maybe_pause
exit /b 0

:maybe_pause
if defined RESTORE_NO_PAUSE exit /b 0
pause
exit /b 0
