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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKEND_DIR="${ROOT_DIR}/backend"
FRONTEND_DIR="${ROOT_DIR}/frontend"

BACKEND_PORT="${BACKEND_PORT:-5001}"
FRONTEND_PORT="${FRONTEND_PORT:-5200}"
BACKEND_HOST="${BACKEND_HOST:-127.0.0.1}"
BACKEND_URL="http://${BACKEND_HOST}:${BACKEND_PORT}"

read -r -p "Backend: npm install ausfuehren? (y/N) " backend_install_choice
if [[ "$backend_install_choice" =~ ^([YyJj]|[Yy]es|[Jj]a)$ ]]; then
  BACKEND_NPM_INSTALL="1"
else
  BACKEND_NPM_INSTALL="0"
fi

read -r -p "Frontend: npm install ausfuehren? (y/N) " frontend_install_choice
if [[ "$frontend_install_choice" =~ ^([YyJj]|[Yy]es|[Jj]a)$ ]]; then
  FRONTEND_NPM_INSTALL="1"
else
  FRONTEND_NPM_INSTALL="0"
fi

cleanup() {
  echo ""
  echo "Stopping processes..."
  if [[ -n "${BACKEND_PID:-}" ]]; then
    kill -TERM "$BACKEND_PID" 2>/dev/null || true
    wait "$BACKEND_PID" 2>/dev/null || true
  fi
  if [[ -n "${FRONTEND_PID:-}" ]]; then
    kill -TERM "$FRONTEND_PID" 2>/dev/null || true
    wait "$FRONTEND_PID" 2>/dev/null || true
  fi
}
trap cleanup INT TERM EXIT

echo "Starting backend on port ${BACKEND_PORT}..."
(
  cd "$BACKEND_DIR"
  if [[ "$BACKEND_NPM_INSTALL" == "1" ]]; then
    npm install
  else
    echo "Backend npm install uebersprungen."
  fi
  PORT="$BACKEND_PORT" npm run dev
) &

BACKEND_PID=$!

echo "Starting frontend on port ${FRONTEND_PORT}..."
(
  cd "$FRONTEND_DIR"
  if [[ "$FRONTEND_NPM_INSTALL" == "1" ]]; then
    npm install
  else
    echo "Frontend npm install uebersprungen."
  fi
  VITE_BACKEND_URL="$BACKEND_URL" npm run dev -- --port "$FRONTEND_PORT" --strictPort
) &

FRONTEND_PID=$!

echo ""
echo "Backend PID: $BACKEND_PID"
echo "Frontend PID: $FRONTEND_PID"
echo "Press Ctrl+C to stop everything"
echo ""

wait "$BACKEND_PID" "$FRONTEND_PID"
