@echo off
setlocal enabledelayedexpansion

echo ==========================================
echo     MEDiThings Bladder Patch Programming
echo     (DEBUG MODE - No Readback Protection)
echo ==========================================

REM -----------------------------------------------------
REM Set script directory as base path
REM -----------------------------------------------------
cd /d "%~dp0"
echo Working directory: %CD%

REM -----------------------------------------------------
REM Create hex output folder
REM -----------------------------------------------------
if not exist hex mkdir hex

REM -----------------------------------------------------
REM 1. Copy HEX files (with verification)
REM -----------------------------------------------------
echo [1/6] Copying HEX files...

set "APP_SRC=..\pca10056\s140\arm5_no_packs\_build\nrf52840_xxaa.hex"
set "BOOT_SRC=..\..\..\dfu\secure_bootloader\pca10056_s140_ble\arm5_no_packs\_build\nrf52840_xxaa_s140.hex"

REM Check source files exist
if not exist "%APP_SRC%" (
    echo ERROR: Application HEX not found: %APP_SRC%
    pause
    exit /b 1
)

if not exist "%BOOT_SRC%" (
    echo ERROR: Bootloader HEX not found: %BOOT_SRC%
    pause
    exit /b 1
)

REM Copy with /Y to overwrite without prompt
copy /Y "%APP_SRC%" hex\app.hex
if %errorlevel% neq 0 (
    echo ERROR: Failed to copy app.hex
    pause
    exit /b 1
)
echo   - app.hex copied OK

copy /Y "%BOOT_SRC%" hex\boot.hex
if %errorlevel% neq 0 (
    echo ERROR: Failed to copy boot.hex
    pause
    exit /b 1
)
echo   - boot.hex copied OK

REM -----------------------------------------------------
REM 2. Generate Bootloader DFU Settings
REM -----------------------------------------------------
echo [2/6] Generating Bootloader DFU settings...
nrfutil settings generate ^
    --family NRF52840 ^
    --application hex\app.hex ^
    --application-version 1 ^
    --bootloader-version 1 ^
    --bl-settings-version 2 ^
    hex\settings.hex

if %errorlevel% neq 0 (
    echo ERROR: nrfutil settings failed.
    pause
    exit /b 1
)

REM -----------------------------------------------------
REM 3. Merge HEX (SoftDevice + Application)
REM -----------------------------------------------------
echo [3/6] Merging SoftDevice + Application...
mergehex.exe --merge s140_nrf52_7.2.0_softdevice.hex hex\app.hex --output hex\part1.hex

if %errorlevel% neq 0 (
    echo ERROR: mergehex part1 failed.
    pause
    exit /b 1
)

REM -----------------------------------------------------
REM 4. Merge HEX (Bootloader + Settings)
REM -----------------------------------------------------
echo [4/6] Merging Bootloader + Settings...
mergehex.exe --merge hex\boot.hex hex\settings.hex --output hex\part2.hex

if %errorlevel% neq 0 (
    echo ERROR: mergehex part2 failed.
    pause
    exit /b 1
)

REM -----------------------------------------------------
REM 5. Final HEX merge (Combine everything)
REM -----------------------------------------------------
echo [5/6] Creating final combined HEX...
mergehex.exe --merge hex\part1.hex hex\part2.hex --output hex\firmware_all.hex

if %errorlevel% neq 0 (
    echo ERROR: mergehex final merge failed.
    pause
    exit /b 1
)

echo Final merged HEX: hex\firmware_all.hex

REM -----------------------------------------------------
REM 6. Detect device SERIAL NUMBER and Flash
REM -----------------------------------------------------
echo [6/6] Detecting device serial number...

for /f %%A in ('
    powershell -Command "(nrfutil device list --json | Select-String '\"type\":\"info\"' | ConvertFrom-Json).data.devices[0].serialNumber"
') do set SERIALNUMBER=%%A

if "%SERIALNUMBER%"=="" (
    echo ERROR: No serial number found.
    pause
    exit /b 1
)

echo Using Serial Number: %SERIALNUMBER%
echo Flashing: program → reset (NO erase, FDS preserved)

REM recover - SKIP to preserve internal flash data
REM erase   - SKIP to preserve FDS/fstorage data

REM program (sector-erase only for hex regions, FDS pages untouched)
nrfutil device program --firmware hex\firmware_all.hex --serial-number %SERIALNUMBER%
if %errorlevel% neq 0 (
    echo.
    echo [WARNING] Program failed - device may have Readback Protection enabled.
    echo           Recover will ERASE ALL flash including FDS data.
    echo.
    set /p RECOVER_YN="Recover and retry? (Y/N): "
    if /i "!RECOVER_YN!"=="Y" (
        echo Recovering device...
        nrfutil device recover --serial-number %SERIALNUMBER%
        if %errorlevel% neq 0 goto flash_fail
        echo Re-programming...
        nrfutil device program --firmware hex\firmware_all.hex --serial-number %SERIALNUMBER%
        if %errorlevel% neq 0 goto flash_fail
    ) else (
        goto flash_fail
    )
)

REM reset
nrfutil device reset --serial-number %SERIALNUMBER%
if %errorlevel% neq 0 goto flash_fail

goto flash_success

:flash_fail
echo ERROR: Flashing failed.
pause
exit /b 1

:flash_success

REM -----------------------------------------------------
REM NOTE: Readback Protection SKIPPED for debugging
REM -----------------------------------------------------
echo ==========================================
echo   Programming Complete! (DEBUG MODE)
echo   No Readback Protection Applied
echo   Internal Flash (FDS) Preserved
echo   %date% %time%
echo ==========================================

REM -----------------------------------------------------
REM Open J-Link RTT Viewer for RTT debugging
REM -----------------------------------------------------
echo Starting J-Link RTT Viewer...

endlocal
