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

rem Project root is parent of this dashboard\ folder
for %%I in ("%~dp0..") do set "ROOT=%%~fI"
cd /d "%ROOT%"

title Optuna Dashboard (presets_fin.db)
echo === Optuna Dashboard (optimize_fin / presets_fin.db) ===
echo Project: %ROOT%
echo Dashboard scripts: %~dp0
echo.

if defined OPTUNA_DASHBOARD_DB (
  set "DB=%OPTUNA_DASHBOARD_DB%"
) else (
  set "DB=%ROOT%\presets_fin.db"
)

if not exist "%DB%" (
  echo MISSING: %DB%
  echo Run the optimizer first ^(run.bat^) so a study database exists.
  echo Or set OPTUNA_DASHBOARD_DB to another sqlite file.
  goto :fail
)

where python >nul 2>&1
if errorlevel 1 (
  echo Python not found on PATH.
  echo Install Python 3 from https://www.python.org/downloads/
  echo and check "Add python.exe to PATH", then re-run this .bat.
  goto :fail
)

if not exist "%ROOT%\.venv\Scripts\python.exe" (
  echo Creating virtualenv at %ROOT%\.venv
  python -m venv "%ROOT%\.venv"
  if errorlevel 1 goto :fail
)

echo Ensuring optuna-dashboard + visualization deps are installed...
"%ROOT%\.venv\Scripts\python.exe" -m pip install --upgrade pip setuptools wheel >nul
rem plotly enables optuna.visualization (dashboard meta: plotlypy_is_available)
"%ROOT%\.venv\Scripts\python.exe" -m pip install "optuna>=4.0" optuna-dashboard "plotly>=4.9.0"
if errorlevel 1 goto :fail

rem Absolute path with forward slashes for SQLAlchemy sqlite URL
set "DB_URL=%DB:\=/%"
set "STORAGE=sqlite:///%DB_URL%"
if not defined OPTUNA_DASHBOARD_PORT set "OPTUNA_DASHBOARD_PORT=8080"
if not defined OPTUNA_DASHBOARD_PLOT_OBJECTIVE set "OPTUNA_DASHBOARD_PLOT_OBJECTIVE=0"

echo.
echo Storage: %STORAGE%
echo Open:    http://127.0.0.1:%OPTUNA_DASHBOARD_PORT%/
echo Plots:   multi-obj target index %OPTUNA_DASHBOARD_PLOT_OBJECTIVE% ^(OPTUNA_DASHBOARD_PLOT_OBJECTIVE^)
echo Ctrl+C to stop.
echo.
"%ROOT%\.venv\Scripts\python.exe" "%~dp0local_dashboard.py" --host 127.0.0.1 --port %OPTUNA_DASHBOARD_PORT% "%STORAGE%"
set "ERR=%ERRORLEVEL%"
echo.
if not "%ERR%"=="0" (
  echo FAILED ^(exit %ERR%^).
) else (
  echo Done.
)
pause
exit /b %ERR%

:fail
echo.
echo FAILED.
pause
exit /b 1
