#!/usr/bin/env bash

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
FRONTEND_DIR="$ROOT_DIR/frontend"
BRIDGE_PORT="${BENT_DEV_PROXY_PORT:-8787}"
BRIDGE_PID=""
API_BASE_URL_ENV_FILE="$FRONTEND_DIR/.env.local"
USE_LOCAL_BRIDGE="1"

if [[ -f "$API_BASE_URL_ENV_FILE" ]]; then
  API_BASE_URL_VALUE="$(grep -E '^NUXT_PUBLIC_API_BASE_URL=' "$API_BASE_URL_ENV_FILE" | tail -n 1 | cut -d= -f2- || true)"

  case "$API_BASE_URL_VALUE" in
    http://127.0.0.1:*|https://127.0.0.1:*|http://localhost:*|https://localhost:*)
      USE_LOCAL_BRIDGE="1"
      ;;
    *)
      USE_LOCAL_BRIDGE="0"
      ;;
  esac
fi

cleanup() {
  if [[ -n "$BRIDGE_PID" ]] && kill -0 "$BRIDGE_PID" >/dev/null 2>&1; then
    kill "$BRIDGE_PID" >/dev/null 2>&1 || true
    wait "$BRIDGE_PID" 2>/dev/null || true
  fi
}

trap cleanup EXIT INT TERM

if [[ "$USE_LOCAL_BRIDGE" == "1" ]]; then
  if ! lsof -nP -iTCP:"$BRIDGE_PORT" -sTCP:LISTEN >/dev/null 2>&1; then
    node "$ROOT_DIR/scripts/dev-api-bridge.mjs" &
    BRIDGE_PID=$!

    for _ in {1..40}; do
      if lsof -nP -iTCP:"$BRIDGE_PORT" -sTCP:LISTEN >/dev/null 2>&1; then
        break
      fi

      sleep 0.25
    done

    if ! lsof -nP -iTCP:"$BRIDGE_PORT" -sTCP:LISTEN >/dev/null 2>&1; then
      echo "Local API bridge did not start on port $BRIDGE_PORT" >&2
      exit 1
    fi
  fi
fi

cd "$FRONTEND_DIR"

NUXT_ARGS=("$@")
NUXT_ARGS_STRING=" ${NUXT_ARGS[*]-} "

if [[ "$NUXT_ARGS_STRING" != *" --host "* ]] && [[ "$NUXT_ARGS_STRING" != *" -h "* ]]; then
  NUXT_ARGS+=(--host "${NUXT_HOST:-::1}")
fi

if [[ "$NUXT_ARGS_STRING" != *" --port "* ]] && [[ "$NUXT_ARGS_STRING" != *" -p "* ]]; then
  NUXT_ARGS+=(--port "${NUXT_PORT:-3000}")
fi

npx nuxt dev --dotenv .env.local "${NUXT_ARGS[@]}"
