#!/usr/bin/env bash
# Ensure one runner-owned CDP console forwarder is alive for this Mobile slot.
set -uo pipefail

TARGET="$PWD"
PORT="${WATCHER_PORT:-${METRO_PORT:-}}"
QUIET=false

while [ "$#" -gt 0 ]; do
  case "$1" in
    --target) [ "$#" -ge 2 ] || { echo "Missing value for --target" >&2; exit 2; }; TARGET="$2"; shift 2 ;;
    --port)   [ "$#" -ge 2 ] || { echo "Missing value for --port" >&2; exit 2; }; PORT="$2"; shift 2 ;;
    --quiet)  QUIET=true; shift ;;
    -h|--help)
      printf 'Usage: start-console-forwarder.sh [--target <dir>] [--port <port>] [--quiet]\n'
      exit 0
      ;;
    *) printf 'start-console-forwarder: unknown arg: %s\n' "$1" >&2; exit 2 ;;
  esac
done

[ "${METAMASK_RECIPE_CONSOLE_FORWARD:-1}" != "0" ] || exit 0
TARGET="$(cd "$TARGET" && pwd -P)"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ -z "$PORT" ] && command -v node >/dev/null 2>&1; then
  PORT="$(APP_ROOT="$TARGET" CONFIG_PATH="$SCRIPT_DIR/bridge-runtime/lib/config.cjs" node -e "process.stdout.write(String(require(process.env.CONFIG_PATH).resolvePort()))")"
fi
PORT="${PORT:-8081}"
# shellcheck disable=SC1091
. "$SCRIPT_DIR/../shared/harness-path.sh"
LOG_DIR="$TARGET/$(recipe_runtime_dir)" || exit 1
FORWARDER="$SCRIPT_DIR/bridge-runtime/console-forwarder.cjs"
PID_FILE="$LOG_DIR/console-forwarder.pid"
APP_LOG_FILE="$LOG_DIR/app-console.log"

{ [ -f "$FORWARDER" ] && command -v node >/dev/null 2>&1; } || exit 0
mkdir -p "$LOG_DIR"

stopped_pids=()
stop_forwarder() {
  local pid="$1"
  case " ${stopped_pids[*]-} " in
    *" $pid "*) return ;;
  esac
  stopped_pids+=("$pid")
  kill "$pid" 2>/dev/null || true
  for _ in {1..20}; do
    kill -0 "$pid" 2>/dev/null || return
    sleep 0.05
  done
  kill -KILL "$pid" 2>/dev/null || true
}

# One debugger owns a React Native page. Reap any collector for this Metro port,
# including one left by an older globally installed harness.
while read -r pid cmd; do
  case "$cmd" in
    *console-forwarder.cjs*" --port $PORT "*|*console-forwarder.cjs*" --port=$PORT "*)
      stop_forwarder "$pid"
      ;;
  esac
done < <(ps -axo pid=,command= 2>/dev/null || true)

if [ -f "$PID_FILE" ]; then
  old_pid="$(cat "$PID_FILE" 2>/dev/null || true)"
  if [ -n "$old_pid" ]; then
    case "$(ps -p "$old_pid" -o command= 2>/dev/null)" in
      *console-forwarder.cjs*) stop_forwarder "$old_pid" ;;
    esac
  fi
  rm -f "$PID_FILE"
fi

: > "$APP_LOG_FILE"
pid="$(node "$SCRIPT_DIR/launch-console-forwarder.cjs" \
  --port "$PORT" \
  --out "$APP_LOG_FILE" \
  --err "$LOG_DIR/console-forwarder.err")" || exit 1
printf '%s\n' "$pid" > "$PID_FILE"

# A successful launch must never claim capture when the collector died at boot.
sleep 0.1
if ! kill -0 "$pid" 2>/dev/null; then
  rm -f "$PID_FILE"
  printf 'start-console-forwarder: collector exited during startup; inspect %s\n' \
    "$LOG_DIR/console-forwarder.err" >&2
  exit 1
fi
[ "$QUIET" = true ] || printf 'Device console → app-console.log (CDP forwarder pid %s)\n' "$pid" >&2
