#!/usr/bin/env bash
# dev.sh — Bootstrap the Soldered Warehouse App v4.0.0 development environment
set -e

VENV_DIR=".venv"
PYTHON="${PYTHON:-python3}"

echo "==> Soldered Warehouse App v4.0.0 — dev setup"

# ── 1. Create virtualenv if it doesn't exist ──────────────────────────────────
if [ ! -d "$VENV_DIR" ]; then
    echo "--> Creating virtualenv at $VENV_DIR"
    "$PYTHON" -m venv "$VENV_DIR"
else
    echo "--> Virtualenv already exists at $VENV_DIR"
fi

# ── 2. Activate it ────────────────────────────────────────────────────────────
# shellcheck disable=SC1091
source "$VENV_DIR/bin/activate"
echo "--> Activated: $(python --version)"

# ── 3. Upgrade pip + install requirements ─────────────────────────────────────
echo "--> Installing requirements…"
pip install --upgrade pip --quiet
pip install -r requirements.txt --quiet
echo "--> Dependencies installed"

# ── 4. Create .env if it doesn't exist ───────────────────────────────────────
if [ ! -f ".env" ]; then
    echo "--> Copying .env.example → .env (edit it before running)"
    cp .env.example .env
else
    echo "--> .env already exists"
fi

# ── 5. Run the app ────────────────────────────────────────────────────────────
echo ""
echo "==> Starting Flask dev server on http://localhost:8080"
echo "    (Press Ctrl+C to stop)"
echo ""

# Wait until port 8080 is accepting connections, then open the browser
(until nc -z localhost 8080 2>/dev/null; do sleep 0.2; done && open "http://localhost:8080") &

python run.py
