@echo off
setlocal
chcp 65001 >nul
title dsh-desktop-tool repair: retraction rows

rem Repair session logs that an early build (shipped as dsh-editor-pro) wrote with
rem an empty system/message replacement outside an open turn+step.
rem
rem Default: list only. Nothing is written unless this script is run with --apply,
rem and even then it asks for a typed confirmation.
rem MUST run while DSH is closed: a running Host keeps appending to the same log.

set "APPLY=0"
if /I "%~1"=="--apply" set "APPLY=1"
if /I "%~2"=="--apply" set "APPLY=1"

set "NODE_EXE=node"
where node >nul 2>nul
if errorlevel 1 set "NODE_EXE=%USERPROFILE%\.dsh\dsh-runtimes\dsh-primary-runtime\dependencies\node\bin\node.exe"

if "%APPLY%"=="0" goto :preview
goto :confirm

:preview
echo ---- current state: read only, nothing is written ----
"%NODE_EXE%" "%~dp0repair-retraction-rows.mjs" --list
echo.
echo Nothing was written.
echo To rewrite the sessions listed above, run this script again with --apply.
echo.
pause
exit /b 0

:confirm
tasklist /FI "IMAGENAME eq DeepSeek Harness.exe" 2>nul | find /I "DeepSeek Harness.exe" >nul
if not errorlevel 1 (
  echo.
  echo [X] DeepSeek Harness is still running.
  echo     Quit DSH completely, then run this script again.
  echo.
  pause
  exit /b 1
)

echo ---- sessions that will be rewritten ----
"%NODE_EXE%" "%~dp0repair-retraction-rows.mjs" --list
echo.
echo This REWRITES every repairable session log above.
echo A backup is written next to each file as session.v4.jsonl.zstd.bak-^<time^>.
echo.
set "ANSWER="
set /p "ANSWER=Type YES to rewrite these logs: "
if /I not "%ANSWER%"=="YES" (
  echo.
  echo Cancelled. Nothing was written.
  pause
  exit /b 1
)

echo.
"%NODE_EXE%" "%~dp0repair-retraction-rows.mjs" --all --apply
echo.
echo Done. Start DSH again; the repaired sessions load normally.
echo.
pause
