#!/usr/bin/env bash
# serve-dashboard: Launch localhost De Stijl dashboard
# Runs build-graph to generate fresh data, starts Python http.server,
# opens browser (WSL-aware), and stays alive until Ctrl+C

set -euo pipefail

ROOM_DIR="${ROOM_DIR:-./room}"
PREFERRED_PORT="${1:-8420}"
MAX_PORT=8430

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DASHBOARD_DIR="$(cd "${SCRIPT_DIR}/../dashboard" && pwd)"

# ── Step 1: Resolve room directory (absolute path) ──
if [ ! -d "$ROOM_DIR" ]; then
  echo "ERROR: Room directory not found: $ROOM_DIR"
  echo "Set ROOM_DIR or ensure ./room/ exists in your workspace"
  exit 1
fi
ROOM_DIR="$(cd "$ROOM_DIR" && pwd)"

# ── Step 2: Generate fresh graph data into the dashboard directory ──
# Phase 162-02 (R4): the dashboard graph.json feed is now SPINE-SOURCED via
# build-graph-from-sqlite.cjs (navigation.getGraphExport), not the bash
# scripts/build-graph wikilink/filesystem scanner. One id space, no orphans.
echo "Building graph data from ${ROOM_DIR}..."
node "${SCRIPT_DIR}/build-graph-from-sqlite.cjs" "$ROOM_DIR" "${DASHBOARD_DIR}/graph.json"

# ── Step 3: Find available port ──
# Also generates standalone export alongside the dashboard
bash "${SCRIPT_DIR}/generate-standalone" "$ROOM_DIR" "${DASHBOARD_DIR}" 2>/dev/null || true

find_port() {
  local port="$1"
  local max="$2"
  while [ "$port" -le "$max" ]; do
    if python3 -c "import socket; s=socket.socket(); s.bind(('',${port})); s.close()" 2>/dev/null; then
      echo "$port"
      return 0
    fi
    port=$((port + 1))
  done
  return 1
}

PORT=$(find_port "$PREFERRED_PORT" "$MAX_PORT")
if [ -z "$PORT" ]; then
  echo "ERROR: No available port in range ${PREFERRED_PORT}-${MAX_PORT}"
  exit 1
fi

# ── Step 4: Start Python http.server in background ──
SERVER_PID=""
cleanup() {
  if [ -n "$SERVER_PID" ] && kill -0 "$SERVER_PID" 2>/dev/null; then
    kill "$SERVER_PID" 2>/dev/null || true
    wait "$SERVER_PID" 2>/dev/null || true
  fi
  echo ""
  echo "Dashboard stopped."
}
trap cleanup EXIT INT TERM

python3 -m http.server "$PORT" --directory "$DASHBOARD_DIR" &>/dev/null &
SERVER_PID=$!

# Brief pause to let server start
sleep 0.5

# Verify server started
if ! kill -0 "$SERVER_PID" 2>/dev/null; then
  echo "ERROR: Failed to start server on port ${PORT}"
  exit 1
fi

# ── Step 5: Open browser (cross-platform) ──
URL="http://localhost:${PORT}"

open_browser() {
  local url="$1"
  if grep -qi microsoft /proc/version 2>/dev/null; then
    # WSL: use Windows browser
    cmd.exe /c start "" "$url" 2>/dev/null || true
  elif [ "$(uname)" = "Darwin" ]; then
    open "$url" 2>/dev/null || true
  elif command -v xdg-open >/dev/null 2>&1; then
    xdg-open "$url" >/dev/null 2>&1 &
  else
    echo "Open ${url} in your browser"
  fi
}

open_browser "$URL"

# ── Step 6: Print status ──
echo ""
echo "Dashboard running at ${URL} (PID: ${SERVER_PID})"
echo "Press Ctrl+C to stop"
echo ""

# ── Step 7: Wait for server process ──
wait "$SERVER_PID"
