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

title Optuna Dashboard (presets.db)
echo === Optuna Dashboard (presets.db) ===
echo Project: %CD%
echo.

if not exist "presets.db" (
  echo MISSING: presets.db
  echo Run the optimizer first ^(run.bat^) so a study database exists.
  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 ".venv\Scripts\python.exe" (
  echo Creating virtualenv at .venv
  python -m venv .venv
  if errorlevel 1 goto :fail
)

echo Ensuring optuna-dashboard + visualization deps are installed...
".venv\Scripts\python.exe" -m pip install --upgrade pip setuptools wheel >nul
rem plotly enables optuna.visualization (dashboard meta: plotlypy_is_available)
".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=%CD%\presets.db"
set "DB=%DB:\=/%"
set "STORAGE=sqlite:///%DB%"
if not defined OPTUNA_DASHBOARD_PORT set "OPTUNA_DASHBOARD_PORT=8080"
rem Multi-obj studies need a plot target; local_dashboard.py defaults to this index.
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.
".venv\Scripts\python.exe" local_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
