@echo off
setlocal enabledelayedexpansion
title AutoBurn PC-Local Setup
chcp 437 >nul

:: Detect --no-pause flag: when set, all exit points skip the final pause.
:: Used by automation (the AI agent's Bash tool). Default = pause so users
:: launching via double-click / "Run as administrator" can read the output.
set "NO_PAUSE=0"
if /i "%~1"=="--no-pause" set "NO_PAUSE=1"

echo ================================================
echo   AutoBurn PC-Local Setup
echo   Hi3516CV610 burn tool (PC-local variant)
echo ================================================
echo.

:: Request admin privileges (TFTP needs port 69)
net session >nul 2>&1
if %errorLevel% neq 0 (
    echo [!] Admin rights required. Restarting as administrator...
    powershell -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
    exit /b
)
echo [OK] Admin rights confirmed
echo.

:: Check Python
echo [1/4] Checking Python...
python --version >nul 2>&1
if %errorLevel% neq 0 (
    echo [!] Python not found.
    echo     About to install Python 3.12 via winget.
    echo       Package : Python.Python.3.12
    echo       Source  : Microsoft winget default (official Python.org MSI)
    echo.
    winget install Python.Python.3.12 --silent --accept-package-agreements --accept-source-agreements
    if !errorLevel! neq 0 (
        echo.
        echo [ERROR] winget install failed. Please install Python manually:
        echo         https://www.python.org/downloads/
        echo         Make sure to check "Add Python to PATH"
        echo         Then re-run this script.
        goto :failure
    )
    for /f "tokens=2*" %%a in ('reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path 2^>nul') do set "PATH=%%b;%PATH%"
    for /f "tokens=2*" %%a in ('reg query "HKCU\Environment" /v Path 2^>nul') do set "PATH=%%b;%PATH%"
    python --version >nul 2>&1
    if !errorLevel! neq 0 (
        echo [!] Python installed but PATH not refreshed.
        echo     Please close this window and run the script again.
        goto :failure
    )
)
for /f "tokens=*" %%v in ('python --version 2^>^&1') do echo [OK] %%v
echo.

:: Install pip packages (PC-local: images already on PC, only need TFTP + serial)
echo [2/4] Installing Python packages...
echo       tftpy    - local TFTP server (pure Python)
echo       pyserial - serial port communication
echo       Source   : PyPI default (https://pypi.org/)
echo.
python -m pip install --quiet --upgrade pip
python -m pip install --quiet tftpy pyserial
if %errorLevel% neq 0 (
    echo [ERROR] pip install failed. Check network connection.
    goto :failure
)
echo [OK] Packages installed
echo.

:: Create default image directory (for burn images; config.ini's [paths] image_dir points here)
echo [3/4] Creating directories...
if not exist "D:\tftp" (
    mkdir "D:\tftp"
    echo [OK] Created D:\tftp  (default image directory; put burn images here)
) else (
    echo [OK] D:\tftp already exists
)
echo.

:: Create config.ini from template
echo [4/4] Checking config.ini...
set "SCRIPT_DIR=%~dp0"
set "CONFIG_FILE=%SCRIPT_DIR%config.ini"

if not exist "%CONFIG_FILE%" (
    set "EXAMPLE_FILE=%SCRIPT_DIR%config.example.ini"
    if exist "!EXAMPLE_FILE!" (
        copy "!EXAMPLE_FILE!" "%CONFIG_FILE%" >nul
        echo [OK] config.ini created from template
        echo [!] Please edit config.ini and fill in all required fields before burning
    ) else (
        echo [!] config.example.ini not found. Please create config.ini manually.
    )
) else (
    echo [OK] config.ini found: %CONFIG_FILE%
)
echo.

:: List available serial ports
echo Available serial ports:
python -c "import serial.tools.list_ports; ports=list(serial.tools.list_ports.comports()); [print(f'  {p.device} - {p.description}') for p in ports] if ports else print('  (no serial ports detected)')"
echo.

:: Done
echo ================================================
echo   Setup complete!
echo.
echo   Next steps:
echo   1. Copy compiled images into the image directory (default: D:\tftp)
echo      Needed files depend on flash type:
echo        NOR  : boot_image.bin nor_env.bin  uImage rootfs_hi3516cv610_64k.jffs2
echo        NAND : boot_image.bin nand_env.bin uImage rootfs_hi3516cv610_2k_128k_32M.ubifs
echo        EMMC : boot_image.bin emmc_env.bin uImage rootfs_hi3516cv610.ext4
echo.
echo   2. Edit config.ini and fill in:
echo      [paths]   image_dir   (folder created in step 1)
echo      [network] pc_ip (usually 192.168.1.100), board_ip
echo      [board]   flash_type (NOR/NAND/EMMC), serial_port (AUTO or COM3)
echo.
echo   3. Validate config:
echo      python check_config.py
echo.
echo   4. Burn (run PowerShell/cmd as administrator, TFTP needs port 69):
echo      python autoburn.py
echo ================================================

:: Success exit. Pause so user can read output unless --no-pause was passed.
if "%NO_PAUSE%"=="0" pause
exit /b 0

:failure
:: Failure exit. Same pause behavior — user-launched windows shouldn't slam shut
:: on error, automation shouldn't block.
if "%NO_PAUSE%"=="0" pause
exit /b 1
