#!/usr/bin/env bash
# Launch Optuna Dashboard for presets.db (Debian-like).
# Double-click friendly: reopens in a terminal if needed.
set -euo pipefail

ROOT="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}" 2>/dev/null || realpath "${BASH_SOURCE[0]}" 2>/dev/null || echo "${BASH_SOURCE[0]}")")" && pwd)"
cd "$ROOT"

# Re-open in a terminal when launched from a GUI file manager
if [[ -z "${RUN_DASHBOARD_IN_TERM:-}" ]] && { [[ ! -t 1 ]] || [[ -z "${TERM:-}" ]]; }; then
  export RUN_DASHBOARD_IN_TERM=1
  if command -v gnome-terminal >/dev/null 2>&1; then
    exec gnome-terminal --working-directory="$ROOT" -- bash "$ROOT/dashboard.sh" "$@"
  elif command -v xfce4-terminal >/dev/null 2>&1; then
    exec xfce4-terminal --working-directory="$ROOT" -e "bash \"$ROOT/dashboard.sh\""
  elif command -v konsole >/dev/null 2>&1; then
    exec konsole --workdir "$ROOT" -e bash "$ROOT/dashboard.sh" "$@"
  elif command -v x-terminal-emulator >/dev/null 2>&1; then
    exec x-terminal-emulator -e bash -lc "cd \"$ROOT\" && exec bash \"$ROOT/dashboard.sh\" $*"
  elif command -v xterm >/dev/null 2>&1; then
    exec xterm -e bash -lc "cd \"$ROOT\" && exec bash \"$ROOT/dashboard.sh\" $*"
  fi
fi

hold() {
  local code=${1:-0}
  echo
  if [[ $code -ne 0 ]]; then
    echo "FAILED (exit $code)."
  else
    echo "Done."
  fi
  if [[ -n "${RUN_DASHBOARD_IN_TERM:-}" ]] || [[ ! -t 0 ]]; then
    read -r -p "Press Enter to close…" _ || true
  fi
  exit "$code"
}
trap 'hold $?' EXIT

echo "=== Optuna Dashboard (presets.db) ==="
echo "Project: $ROOT"
echo

DB="$ROOT/presets.db"
if [[ ! -f "$DB" ]]; then
  echo "MISSING: presets.db"
  echo "Run the optimizer first (run.sh) so a study database exists."
  exit 1
fi

# System packages
need_apt=()
command -v python3 >/dev/null 2>&1 || need_apt+=(python3)
python3 -m venv -h >/dev/null 2>&1 || need_apt+=(python3-venv)
python3 -c "import ensurepip" 2>/dev/null || need_apt+=(python3-venv)
command -v pip3 >/dev/null 2>&1 || python3 -m pip -h >/dev/null 2>&1 || need_apt+=(python3-pip)

if [[ ${#need_apt[@]} -gt 0 ]]; then
  echo "Installing system packages: ${need_apt[*]}"
  if ! command -v apt-get >/dev/null 2>&1; then
    echo "apt-get not found; install Python 3 + venv manually."
    exit 1
  fi
  if [[ "$(id -u)" -eq 0 ]]; then
    apt-get update -y
    DEBIAN_FRONTEND=noninteractive apt-get install -y "${need_apt[@]}"
  elif command -v sudo >/dev/null 2>&1; then
    sudo apt-get update -y
    sudo DEBIAN_FRONTEND=noninteractive apt-get install -y "${need_apt[@]}"
  else
    echo "Need root for: ${need_apt[*]}"
    exit 1
  fi
fi

VENV="$ROOT/.venv"
if [[ ! -d "$VENV" ]]; then
  echo "Creating virtualenv at $VENV"
  python3 -m venv "$VENV"
fi
# shellcheck disable=SC1091
source "$VENV/bin/activate"

echo "Ensuring optuna-dashboard + visualization deps are installed…"
python -m pip install --upgrade pip setuptools wheel >/dev/null
# plotly enables optuna.visualization (dashboard meta: plotlypy_is_available)
python -m pip install "optuna>=4.0" optuna-dashboard "plotly>=4.9.0"

STORAGE="sqlite:///${DB}"
PORT="${OPTUNA_DASHBOARD_PORT:-8080}"
# Multi-obj studies need a plot target; local_dashboard.py defaults to this index.
export OPTUNA_DASHBOARD_PLOT_OBJECTIVE="${OPTUNA_DASHBOARD_PLOT_OBJECTIVE:-0}"

echo
echo "Storage: $STORAGE"
echo "Open:    http://127.0.0.1:${PORT}/"
echo "Plots:   multi-obj target index ${OPTUNA_DASHBOARD_PLOT_OBJECTIVE} (OPTUNA_DASHBOARD_PLOT_OBJECTIVE)"
echo "Ctrl+C to stop."
echo
exec python "$ROOT/local_dashboard.py" --host 127.0.0.1 --port "$PORT" "$STORAGE"
