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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
source "$ROOT/scripts/env.sh"

ADDR="${ADDR:-localhost:8788}"

# Auto-stop if already running on the same port
if command -v lsof >/dev/null 2>&1; then
  pids=$(lsof -t -i "@${ADDR#*:}:${ADDR##*:}" 2>/dev/null)
  if [[ -n "$pids" ]]; then
    echo "Stopping existing goondex on $ADDR (pids: $pids)"
    kill $pids 2>/dev/null || true
    sleep 0.5
  fi
fi

# Build if missing
if [[ ! -x "$ROOT/bin/goondex" ]]; then
  echo "Binary not found; building first..."
  "$ROOT/scripts/build.sh"
fi

echo "Starting Goondex web UI on http://$ADDR"
"$ROOT/bin/goondex" web --addr "$ADDR"
