@echo off
setlocal EnableExtensions EnableDelayedExpansion
cd /d "%~dp0"

set "ROOT=%CD%"
set "RESEARCH=%ROOT%\ClinicalReasoningDatabase\research"
set "LOGDIR=%ROOT%\Logs"
set "LOG=%LOGDIR%\research-workbench.log"
if not exist "%LOGDIR%" mkdir "%LOGDIR%" >nul 2>nul

set "PY=%ROOT%\Runtime\Python\python.exe"
if not exist "%PY%" (
  for /r "%ROOT%\Runtime\Python" %%F in (python.exe) do if not defined FOUND_PY set "FOUND_PY=%%~fF"
  if defined FOUND_PY set "PY=%FOUND_PY%"
)
if not exist "%PY%" (
  where py.exe >nul 2>nul && set "PY=py.exe"
)
if not defined PY (
  where python.exe >nul 2>nul && set "PY=python.exe"
)

echo ================================================================>>"%LOG%"
echo [%date% %time%] RC8 Research Workbench launch>>"%LOG%"
echo Root: %ROOT%>>"%LOG%"
echo Research: %RESEARCH%>>"%LOG%"
echo Python: %PY%>>"%LOG%"

if not exist "%RESEARCH%\server.py" (
  echo ERROR: Missing %RESEARCH%\server.py
  echo ERROR: Missing server.py>>"%LOG%"
  pause
  exit /b 1
)
if not exist "%RESEARCH%\research_engine.py" (
  echo ERROR: Missing %RESEARCH%\research_engine.py
  echo ERROR: Missing research_engine.py>>"%LOG%"
  pause
  exit /b 1
)
if not defined PY (
  echo ERROR: Python runtime not found.
  echo Run Control Center option 5 to repair runtimes.
  echo ERROR: Python runtime not found.>>"%LOG%"
  pause
  exit /b 1
)

set "PYTHONPATH=%ROOT%\ClinicalReasoningDatabase;%RESEARCH%;%PYTHONPATH%"
cd /d "%ROOT%\ClinicalReasoningDatabase"

echo Running import self-test...
"%PY%" -c "from research.research_engine import ResearchEngine; print('ResearchEngine import OK')" >>"%LOG%" 2>&1
if errorlevel 1 (
  echo.
  echo Research engine import failed.
  echo See:
  echo   %LOG%
  echo.
  type "%LOG%"
  pause
  exit /b 1
)

echo Starting Clinical Research Workbench...
echo Browser address: http://127.0.0.1:8765
echo Log: %LOG%
echo.
"%PY%" -m research.server >>"%LOG%" 2>&1
set "RC=%ERRORLEVEL%"

if not "%RC%"=="0" (
  echo.
  echo Research Workbench exited with code %RC%.
  echo See:
  echo   %LOG%
  echo.
  type "%LOG%"
  pause
)
exit /b %RC%
