@echo off
setlocal ENABLEDELAYEDEXPANSION

REM ======================================================================
REM                   COLOR DEFINITIONS (ANSI ESC SEQUENCES)
REM ======================================================================
set "RED=[91m"
set "GREEN=[92m"
set "YELLOW=[93m"
set "RESET=[0m"

REM ======================================================================
REM                         CONFIGURATION
REM ======================================================================

REM Путь к flash8051.exe (лежит в соседней папке ..\c8051\)
set "FLASH_TOOL=%~dp0..\c8051\flash8051.exe"

REM Путь к HEX файлу
set "HEX_FILE=%~dp0master_boot.hex"

REM Серийный номер Debug Adapter (должен быть ДЕСЯТИЧНЫЙ!)
set "SERIAL=EC3005A03C4"

REM ======================================================================
REM                           CHECK FILES
REM ======================================================================

echo %YELLOW%Using tool:%RESET%   "%FLASH_TOOL%"
echo %YELLOW%HEX file:%RESET%     "%HEX_FILE%"
echo %YELLOW%Serial:%RESET%        %SERIAL%
echo.

if not exist "%FLASH_TOOL%" (
    echo %RED%[ERROR] flash8051.exe not found:%RESET%
    echo   "%FLASH_TOOL%"
    echo.
    echo Press any key to exit . . .
    pause >nul
    exit /b 1
)

if not exist "%HEX_FILE%" (
    echo %RED%[ERROR] HEX file not found:%RESET%
    echo   "%HEX_FILE%"
    echo.
    echo Press any key to exit . . .
    pause >nul
    exit /b 1
)

REM ======================================================================
REM                          FLASH PROCESS
REM ======================================================================

echo %YELLOW%Starting flash...%RESET%
echo.

"%FLASH_TOOL%" -sn %SERIAL% -tif c2 -erase -upload "%HEX_FILE%"
set "ERR=%ERRORLEVEL%"

echo.

REM ======================================================================
REM                           RESULT HANDLING
REM ======================================================================

if not "%ERR%"=="0" (
    echo %RED%[ERROR] Flash failed! Error code: %ERR%%RESET%
    echo Check:
    echo   - Debug Adapter connection
    echo   - Target power
    echo   - Correct serial number
    echo   - Valid HEX file
    echo.
    echo Press any key to exit . . .
    pause >nul
    exit /b %ERR%
)

echo %GREEN%[OK] Flash completed successfully.%RESET%
echo.
echo Press any key to exit . . .
pause >nul
exit /b 0
