#!/usr/bin/env bash
# -------------------------------------------------------------
# Debug helper for NexusReader.Web (Blazor Server)
# -------------------------------------------------------------
# 1️⃣  Ensure the port is free before starting the server.
# 2️⃣  Starts the server project in the background.
# 3️⃣  Waits until the HTTP endpoint is reachable.
# 4️⃣  Launches Chrome (or Chromium) with a clean temporary profile
#     and the remote‑debugging port (9222).
# -------------------------------------------------------------

# ---- configuration ------------------------------------------------
SERVER_PROJECT="src/NexusReader.Web/NexusReader.Web.csproj"
APP_URL="http://localhost:5104"
DEBUG_PORT=9222
TMP_PROFILE="/tmp/blazor-chrome-debug"
CHROME_CMD="google-chrome"   # fallback will be tried automatically
# ------------------------------------------------------------------

# Export environment variables for the app
export ASPNETCORE_ENVIRONMENT=Development
export ASPNETCORE_URLS="$APP_URL"

# Free the port if something is already listening on it
PORT=$(echo "$APP_URL" | awk -F[:/] '{print $4}')
if [ -n "$PORT" ]; then
    if lsof -ti:$PORT >/dev/null 2>&1; then
        echo "⚡ Port $PORT is in use – terminating existing process."
        fuser -k $PORT/tcp >/dev/null 2>&1 || kill -9 $(lsof -ti:$PORT) >/dev/null 2>&1
        sleep 1
    fi
fi

# Clean old temporary profile
rm -rf "$TMP_PROFILE"

# Start the server in the background, capture its PID
# We use --no-build because we assume you just built it, 
# and it prevents redundant build output in the console.
dotnet run --project "$SERVER_PROJECT" --launch-profile http &
SERVER_PID=$!
echo "🚀 Blazor Server started (PID=$SERVER_PID). Waiting for $APP_URL …"

# Simple poll loop – wait up to 30 s for the app to become reachable
MAX_WAIT=30
elapsed=0
while ! curl -s "$APP_URL" > /dev/null; do
  sleep 1
  ((elapsed++))
  if (( elapsed >= MAX_WAIT )); then
    echo "❌ Timeout: $APP_URL never responded."
    kill $SERVER_PID 2>/dev/null
    exit 1
  fi
done
echo "✅ App is up! Launching Chrome..."

# Determine which browser binary is available
if command -v "$CHROME_CMD"   > /dev/null; then :; else
  if command -v chromium-browser > /dev/null; then CHROME_CMD="chromium-browser"; else
    if command -v chromium > /dev/null; then CHROME_CMD="chromium"; else
        echo "❌ Neither google-chrome nor chromium-browser found on PATH."
        kill $SERVER_PID 2>/dev/null
        exit 1
    fi
  fi
fi

# Launch Chrome with remote‑debugging and the temporary profile
# Added --headless=new if you are on a server without display, 
# but keeping it interactive as requested.
"$CHROME_CMD" \
  --remote-debugging-port=$DEBUG_PORT \
  --user-data-dir="$TMP_PROFILE" \
  --no-first-run \
  --no-default-browser-check \
  "$APP_URL" &
CHROME_PID=$!

echo "🌐 Chrome launched (PID=$CHROME_PID)."
echo "🔧 Open DevTools via: http://localhost:$DEBUG_PORT"

# keep the script alive until you stop it,
# forwarding signals to both processes.
trap 'echo "Stopping..."; kill $SERVER_PID $CHROME_PID 2>/dev/null' INT TERM EXIT
wait $SERVER_PID
