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

# 2026-05-21 Codex: protect the shared 110 host runner from overlapping
# host-side frontend production builds launched by other repositories.
# This is intentionally a wait gate, not an auto-repair step: it never kills,
# renices, or rewrites another repo's process tree.

ATTEMPTS="${HOST_WEB_BUILD_PRESSURE_ATTEMPTS:-60}"
SLEEP_SECONDS="${HOST_WEB_BUILD_PRESSURE_SLEEP_SECONDS:-10}"
WARN_ONLY="${HOST_WEB_BUILD_PRESSURE_WARN_ONLY:-1}"
PS_COMMAND="${HOST_WEB_BUILD_PRESSURE_PS_COMMAND:-ps -eo pid=,ppid=,pcpu=,pmem=,args= --sort=-pcpu}"

list_foreign_web_builds() {
  bash -c "$PS_COMMAND" | awk '
    BEGIN { IGNORECASE = 1 }
    /[n]ext[\/[:alnum:]._-]*[[:space:]]+build|[t]urbo[[:space:]]+build|[v]ite[[:space:]]+build/ {
      if ($0 ~ /\/workspace\/wooo\/awoooi/) next
      if ($0 ~ /\/Users\/ogt\/awoooi/) next
      if ($0 ~ /\/private\/tmp\/awoooi/) next
      if ($0 ~ /\/app\/apps\/web/) next
      if ($0 ~ /scripts\/ci\/wait-host-web-build-pressure\.sh/) next
      print
    }
  '
}

for attempt in $(seq 1 "$ATTEMPTS"); do
  active_builds="$(list_foreign_web_builds || true)"
  if [ -z "$active_builds" ]; then
    echo "✅ no foreign host web build pressure detected"
    exit 0
  fi

  echo "⏳ foreign host web build pressure detected (attempt ${attempt}/${ATTEMPTS}); waiting ${SLEEP_SECONDS}s"
  printf '%s\n' "$active_builds" | head -n 8
  sleep "$SLEEP_SECONDS"
done

echo "⚠️ foreign host web build pressure still active after ${ATTEMPTS} checks"
if [ "$WARN_ONLY" = "1" ]; then
  echo "⚠️ continuing to avoid a stuck deploy; see ops/runner/README.md for the runner isolation plan"
  exit 0
fi

echo "❌ refusing to start AWOOI image build while foreign host web builds are still active"
exit 1
