@echo off
echo.
echo ========================================
echo   VoiceBox G2 Firmware Flasher
echo ========================================
echo.

REM Find esptool
where esptool.py >nul 2>&1 && set ESPTOOL=esptool.py && goto :found
python -m esptool version >nul 2>&1 && set ESPTOOL=python -m esptool && goto :found
python3 -m esptool version >nul 2>&1 && set ESPTOOL=python3 -m esptool && goto :found
where esptool >nul 2>&1 && set ESPTOOL=esptool && goto :found

echo esptool not found -- installing...
echo.

REM Try to install via pip
python -m pip install esptool >nul 2>&1 && goto :retry
python3 -m pip install esptool >nul 2>&1 && goto :retry
pip install esptool >nul 2>&1 && goto :retry
pip3 install esptool >nul 2>&1 && goto :retry

echo ERROR: Could not install esptool.
echo.
echo Install Python 3 from https://www.python.org/downloads/
echo Then run:  pip install esptool
echo.
pause
exit /b 1

:retry
REM Re-check after install
python -m esptool version >nul 2>&1 && set ESPTOOL=python -m esptool && goto :found
python3 -m esptool version >nul 2>&1 && set ESPTOOL=python3 -m esptool && goto :found
where esptool.py >nul 2>&1 && set ESPTOOL=esptool.py && goto :found
where esptool >nul 2>&1 && set ESPTOOL=esptool && goto :found

echo ERROR: esptool install succeeded but command not found.
echo Close this window, open a new terminal, and try again.
pause
exit /b 1

:found
echo Using: %ESPTOOL%
echo.

REM ── Find and select COM port ──
REM Use esptool's own port detection via Python for reliable results
set PORTLIST=
set PORTCOUNT=0

REM List ports using esptool's serial.tools.list_ports
for /f "tokens=1" %%p in ('python -c "import serial.tools.list_ports; [print(p.device) for p in serial.tools.list_ports.comports()]" 2^>nul') do (
    set /a PORTCOUNT+=1
    set PORT%%PORTCOUNT%%=%%p
    if !PORTCOUNT! == 1 set FIRSTPORT=%%p
    echo   [!PORTCOUNT!] %%p
)

if %PORTCOUNT% == 0 (
    echo ERROR: No COM ports found.
    echo Connect the VoiceBox G2 via USB-C and try again.
    pause
    exit /b 1
)

setlocal enabledelayedexpansion

if %PORTCOUNT% == 1 (
    set PORT=%FIRSTPORT%
    echo Found device: %PORT%
) else (
    echo.
    set /p choice="Select device [1-%PORTCOUNT%]: "
    set PORT=!PORT%choice%!
    if "!PORT!" == "" (
        echo Invalid selection.
        pause
        exit /b 1
    )
    echo Selected: !PORT!
)

echo.
echo Flashing (encrypted)...
echo.
%ESPTOOL% --chip esp32s3 --port %PORT% --baud 460800 ^
  --before default_reset --after hard_reset ^
  write_flash --encrypt --flash_mode dio --flash_freq 80m --flash_size 16MB ^
  0x0 bin/bootloader.bin 0xe000 bin/partition-table.bin 0x16000 bin/ota_data_initial.bin 0x20000 bin/voicebox_g2_qual.bin

echo.
echo Flash complete! Device will reboot.
pause
