@echo off
echo.
echo ==========================================
echo WiFiX-Enhanced Windows Flashing Script
echo ==========================================
echo.

:: Check if PlatformIO is installed
where pio >nul 2>nul
if %errorlevel% neq 0 (
    echo ERROR: PlatformIO not found!
    echo Please install PlatformIO first:
    echo pip install platformio
    echo.
    pause
    exit /b 1
)

:: Display menu
echo Select flash option:
echo 1. Flash ESP32 (Main Controller)
echo 2. Flash BW16 (WiFi Module)
echo 3. Upload Web Files (SPIFFS)
echo 4. Flash All (ESP32 + Web Files)
echo 5. Monitor ESP32 Serial
echo 6. Monitor BW16 Serial
echo 7. Clean Build
echo 8. Full Setup (Flash All + Monitor)
echo.
set /p choice="Enter choice (1-8): "

:: Execute based on choice
if "%choice%"=="1" goto flash_esp32
if "%choice%"=="2" goto flash_bw16
if "%choice%"=="3" goto upload_fs
if "%choice%"=="4" goto flash_all
if "%choice%"=="5" goto monitor_esp32
if "%choice%"=="6" goto monitor_bw16
if "%choice%"=="7" goto clean
if "%choice%"=="8" goto full_setup
echo Invalid choice!
pause
exit /b 1

:flash_esp32
echo.
echo Flashing ESP32...
pio run -e esp32_main --target upload
if %errorlevel% equ 0 (
    echo SUCCESS: ESP32 flashed!
) else (
    echo ERROR: ESP32 flashing failed!
)
pause
goto end

:flash_bw16
echo.
echo Flashing BW16...
pio run -e bw16_deauth --target upload
if %errorlevel% equ 0 (
    echo SUCCESS: BW16 flashed!
) else (
    echo ERROR: BW16 flashing failed!
)
pause
goto end

:upload_fs
echo.
echo Uploading web files (SPIFFS)...
pio run -e esp32_main --target uploadfs
if %errorlevel% equ 0 (
    echo SUCCESS: Web files uploaded!
) else (
    echo ERROR: Web file upload failed!
)
pause
goto end

:flash_all
echo.
echo Flashing ESP32 and web files...
call :flash_esp32
call :upload_fs
echo.
echo All components flashed!
pause
goto end

:monitor_esp32
echo.
echo Starting ESP32 serial monitor...
echo Press Ctrl+C to exit monitor
echo.
pio device monitor -e esp32_main -b 115200
goto end

:monitor_bw16
echo.
echo Starting BW16 serial monitor...
echo Press Ctrl+C to exit monitor
echo.
pio device monitor -e bw16_deauth -b 115200
goto end

:clean
echo.
echo Cleaning build files...
pio run -e esp32_main --target clean
pio run -e bw16_deauth --target clean
echo Build files cleaned!
pause
goto end

:full_setup
echo.
echo Starting full setup...
echo Step 1: Flashing ESP32...
pio run -e esp32_main --target upload
if %errorlevel% neq 0 (
    echo ERROR: ESP32 flashing failed!
    pause
    goto end
)

echo Step 2: Uploading web files...
pio run -e esp32_main --target uploadfs
if %errorlevel% neq 0 (
    echo ERROR: Web file upload failed!
    pause
    goto end
)

echo.
echo SUCCESS: All components flashed!
echo Starting serial monitor...
echo Press Ctrl+C to exit monitor
echo.
pio device monitor -e esp32_main -b 115200
goto end

:end
echo.
echo ==========================================
echo Script completed!
echo ==========================================
echo.