#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
WEB_SRC_DIR="$ROOT_DIR/web/src"
VENV_DIR="$ROOT_DIR/.venv"
SETUP_ONLY=false

if [[ "${1:-}" == "--setup-only" ]]; then
  SETUP_ONLY=true
fi

if [[ ! -d "$VENV_DIR" ]]; then
  echo "Creating virtual environment..."
  python3 -m venv "$VENV_DIR"
fi

# shellcheck disable=SC1091
source "$VENV_DIR/bin/activate"

if [[ ! -f "$VENV_DIR/.deps_installed" ]] || [[ "$WEB_SRC_DIR/requirements.txt" -nt "$VENV_DIR/.deps_installed" ]]; then
  echo "Installing dependencies..."
  pip install -r "$WEB_SRC_DIR/requirements.txt"
  touch "$VENV_DIR/.deps_installed"
fi

if [[ "$SETUP_ONLY" == "true" ]]; then
  echo "Setup complete."
  exit 0
fi

echo "Starting Streamlit app..."
exec streamlit run "$WEB_SRC_DIR/app.py"
