@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

echo ========================================
echo Starting Auto Android Controller
echo ========================================
echo.

REM Get the directory where this batch file is located and navigate to project root
set "SCRIPT_DIR=%~dp0"
set "PROJECT_ROOT=%SCRIPT_DIR%..\.."
cd /d "%PROJECT_ROOT%"

REM Check if npm is available
echo [1/3] Checking npm...
where npm >nul 2>&1
if errorlevel 1 (
    echo Error: npm is not found in PATH
    echo.
    echo Please ensure Node.js is installed and npm is in your system PATH.
    echo You can download Node.js from: https://nodejs.org/
    echo.
    echo If Node.js is installed but npm is not in PATH, you may need to:
    echo 1. Restart your computer after installing Node.js
    echo 2. Or add Node.js to your system PATH manually
    echo.
    pause
    exit /b 1
)
echo npm is available
echo.

REM Check if node_modules exists and key dependencies are installed
echo [2/3] Checking dependencies...
if not exist "node_modules" (
    echo Warning: node_modules not found. Installing dependencies...
    call npm install
    if errorlevel 1 (
        echo Error: Failed to install dependencies
        pause
        exit /b 1
    )
) else (
    echo Dependencies directory found
    REM Check if key dependencies are properly installed
    set "NEED_REINSTALL=0"
    if not exist "node_modules\concurrently\dist\bin\concurrently.js" (
        echo Warning: concurrently module appears incomplete
        set "NEED_REINSTALL=1"
    )
    if not exist "node_modules\rxjs\dist\cjs\index.js" (
        echo Warning: rxjs module appears incomplete
        set "NEED_REINSTALL=1"
    )
    if not exist "node_modules\electron\package.json" (
        echo Warning: electron module appears incomplete
        set "NEED_REINSTALL=1"
    )
    if "!NEED_REINSTALL!"=="1" (
        echo Warning: Key dependencies appear incomplete. Reinstalling...
        call npm install
        if errorlevel 1 (
            echo Error: Failed to reinstall dependencies
            pause
            exit /b 1
        )
        echo Dependencies reinstalled successfully
    ) else (
        echo Dependencies verified
    )
)
echo.

REM Start the application
echo [3/3] Starting application...
echo.
call npm run electron:dev
if errorlevel 1 (
    echo.
    echo Error: Failed to start application
    pause
    exit /b 1
)
