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

cd "$(dirname "$0")"

PORT="${PORT:-8000}"
APP_URL="http://localhost:${PORT}/index.html"
LOG_FILE="${TMPDIR:-/tmp}/ai-night-vision-http-server.log"

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
}
trap cleanup EXIT INT TERM

python3 -m http.server "${PORT}" >"${LOG_FILE}" 2>&1 &
SERVER_PID=$!

sleep 1
if ! kill -0 "${SERVER_PID}" 2>/dev/null; then
  echo "Failed to start Python HTTP server on port ${PORT}."
  echo "Check log: ${LOG_FILE}"
  exit 1
fi

if command -v xdg-open >/dev/null 2>&1; then
  xdg-open "${APP_URL}" >/dev/null 2>&1 || true
elif command -v open >/dev/null 2>&1; then
  open "${APP_URL}" >/dev/null 2>&1 || true
fi

echo "AI Night Vision Camera is running."
echo "Open: ${APP_URL}"
echo "Server log: ${LOG_FILE}"
echo "Keep this window open. Press Ctrl+C to stop."
wait "${SERVER_PID}"
