@echo off

:: Request admin privileges
NET SESSION >nul 2>&1
if %errorLevel% NEQ 0 (
    echo Requesting admin privileges...
    powershell -Command "Start-Process cmd -ArgumentList '/c cd /d \"%~dp0\" && \"%~f0\"' -Verb RunAs"
    exit /b
)

cd /d "%~dp0"

title WASD Mobile Joystick Controller

echo.
echo ================================================
echo          WASD Mobile Joystick Controller
echo ================================================
echo.

set "SCRIPT_DIR=%~dp0"
echo [INFO] Script directory: %SCRIPT_DIR%
echo.

set "ADB_PATH=%SCRIPT_DIR%..\platform-tools\platform-tools\adb.exe"
echo [INFO] ADB path: %ADB_PATH%
echo.

if not exist "%ADB_PATH%" (
    echo [ERROR] ADB not found!
    echo [ERROR] Path: %ADB_PATH%
    echo.
    echo [INFO] Downloading ADB tools...
    echo.
    mkdir "%SCRIPT_DIR%..\platform-tools" 2>nul
    powershell -Command "Invoke-WebRequest -Uri 'https://dl.google.com/android/repository/platform-tools-latest-windows.zip' -OutFile '%SCRIPT_DIR%..\platform-tools.zip' -UseBasicParsing"
    if not exist "%SCRIPT_DIR%..\platform-tools.zip" (
        echo [ERROR] Download failed!
        pause
        exit /b 1
    )
    powershell -Command "Expand-Archive -Path '%SCRIPT_DIR%..\platform-tools.zip' -DestinationPath '%SCRIPT_DIR%..\platform-tools' -Force"
    del "%SCRIPT_DIR%..\platform-tools.zip" 2>nul
    echo.
    echo [INFO] ADB download complete!
    echo.
) else (
    echo [INFO] ADB found
    echo.
)

where py >nul 2>nul
if %errorlevel% neq 0 (
    echo [ERROR] Python not found!
    echo [ERROR] Please install Python 3.6+
    echo [ERROR] Download: https://www.python.org/downloads/
    pause
    exit /b 1
) else (
    echo [INFO] Python found
    echo.
)

py -c "import keyboard" >nul 2>nul
if %errorlevel% neq 0 (
    echo [INFO] Installing keyboard module...
    echo.
    py -m pip install keyboard -i https://pypi.tuna.tsinghua.edu.cn/simple
    echo.
    echo [INFO] keyboard module installed!
    echo.
) else (
    echo [INFO] keyboard module installed
    echo.
)

echo [INFO] Checking ADB devices...
echo.
"%ADB_PATH%" devices
echo.

echo ================================================
echo          Press any key to start...
echo ================================================
echo Controls:
echo   W - Move Up
echo   S - Move Down
echo   A - Move Left
echo   D - Move Right
echo   ESC - Exit
echo ================================================
pause >nul

echo.
echo [INFO] Controller started...
echo [INFO] Press ESC to exit
echo.

py "%SCRIPT_DIR%wasd_control.py"
if %errorlevel% neq 0 (
    echo.
    echo [ERROR] Program error!
    echo [ERROR] Error code: %errorlevel%
    pause
    exit /b %errorlevel%
)

echo.
echo [INFO] Program exited
pause
