#!/usr/bin/env bash
# Ensures the harness web UI is running. Prints the base URL to stdout.
# Identity-aware: probes /api/health, not just any server on the port.
set -euo pipefail

HARNESS_HOME="${HARNESS_HOME:-${HOME}/.harness}"
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
WEB_DIR="${REPO_ROOT}/web"
LOG_FILE="${HARNESS_HOME}/web.log"
PID_FILE="${HARNESS_HOME}/web.pid"
PORT_FILE="${HARNESS_HOME}/web.port"

probe_harness() {
  local port="$1"
  curl -sf --max-time 2 "http://localhost:${port}/api/health" 2>/dev/null \
    | grep -q '"service":"mega-plan-harness"'
}

port_in_use() {
  local port="$1"
  if nc -z 127.0.0.1 "${port}" 2>/dev/null || nc -z ::1 "${port}" 2>/dev/null; then
    return 0
  fi
  return 1
}

find_free_port() {
  local port="${HARNESS_WEB_PORT:-4321}"
  while port_in_use "${port}"; do
    port=$((port + 1))
  done
  echo "${port}"
}

# Scan a range for an already-running, health-verified harness instance —
# astro auto-increments off a busy --port, so a prior instance can be alive
# on a port the saved PORT_FILE never recorded.
find_running_harness() {
  local start="${HARNESS_WEB_PORT:-4321}"
  local end=$((start + 20))
  local port
  for ((port = start; port <= end; port += 1)); do
    if probe_harness "${port}"; then
      echo "${port}"
      return 0
    fi
  done
  return 1
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
# Check if our previously-started server is still up
if [[ -f "${PORT_FILE}" ]]; then
  saved_port="$(cat "${PORT_FILE}")"
  if probe_harness "${saved_port}"; then
    echo "http://localhost:${saved_port}"
    exit 0
  fi
fi

mkdir -p "${HARNESS_HOME}"

if running_port="$(find_running_harness)"; then
  echo "${running_port}" > "${PORT_FILE}"
  echo "http://localhost:${running_port}"
  exit 0
fi

if [[ ! -x "${WEB_DIR}/node_modules/.bin/astro" ]]; then
  echo "notice: web UI not installed at ${WEB_DIR} — skipping (runs are unaffected)" >&2
  exit 0
fi

PORT="$(find_free_port)"
cd "${WEB_DIR}"
nohup node_modules/.bin/astro dev --port "${PORT}" >> "${LOG_FILE}" 2>&1 &
echo $! > "${PID_FILE}"
echo "${PORT}" > "${PORT_FILE}"

# Poll up to 15s (30 × 0.5s)
for i in $(seq 1 30); do
  sleep 0.5
  if probe_harness "${PORT}"; then
    echo "http://localhost:${PORT}"
    exit 0
  fi
done

echo "ERROR: harness web UI did not start on port ${PORT} — see ${LOG_FILE}" >&2
exit 1
fi
