#!/usr/bin/env bash

trap "echo 'Server stopped by user'; exit 0" SIGINT

MAX_BACKOFF=60
FAIL_COUNT=0
PID_FILE="bun.pid"
PORT=${PORT:-3000}
ENTRYPOINT="backend/server.ts"

mkdir -p logs

while true; do
  # Check if previous server PID exists
  if [ -f "$PID_FILE" ]; then
    PREV_PID=$(cat "$PID_FILE")
    if ps -p $PREV_PID > /dev/null 2>&1; then
      echo "Previous server (PID $PREV_PID) still running. Waiting 2 seconds..."
      sleep 2
      continue
    else
      # Clean up stale PID file
      rm "$PID_FILE"
    fi
  fi

  echo "Starting Bun server on port $PORT..." | tee -a logs/server.log

  # Start Bun in background and store PID
  bun run $ENTRYPOINT 2>&1 | tee -a logs/server.log &
  SERVER_PID=$!
  echo $SERVER_PID > "$PID_FILE"

  # Wait for server to exit
  wait $SERVER_PID
  EXIT_CODE=$?

  echo "Server exited with code $EXIT_CODE" | tee -a logs/server.log

  # Remove PID file
  rm -f "$PID_FILE"

  # Backoff logic
  FAIL_COUNT=$((FAIL_COUNT + 1))
  BACKOFF=$((2 ** FAIL_COUNT))
  [ $BACKOFF -gt $MAX_BACKOFF ] && BACKOFF=$MAX_BACKOFF
  JITTER=$((RANDOM % 4))
  SLEEP_TIME=$((BACKOFF + JITTER))

  echo "Restarting in $SLEEP_TIME seconds (failures: $FAIL_COUNT)..." | tee -a logs/server.log
  sleep $SLEEP_TIME

  if [ $FAIL_COUNT -ge 10 ]; then
    echo "High number of failures — cooling down for 5 minutes..." | tee -a logs/server.log
    sleep 300
    FAIL_COUNT=0
  fi

done
