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

EXPECTED_BUILD_SHA="4a5f05a1d46857396cda46dab5913f7d57c303d8467167404a5b3e9c0d227c7a"
REMOTE_HOST="tv"
REMOTE_SERVICE_PORT="19474"
LOCAL_FORWARD_PORT=""
REMOTE_LABEL="com.steipete.oracle.staging.dual-profile.green"
REMOTE_HOME_REL=".oracle-staging/dual-profile-green"
ADMISSION_QUEUE_NAMESPACE="oracle-round-robin:${REMOTE_HOST}:${REMOTE_SERVICE_PORT}:${REMOTE_LABEL}"
CHECK_DEADLINE_SECONDS="${ORACLE_RR_CHECK_DEADLINE_SECONDS:-60}"
WORKTREE="${ORACLE_RR_WORKTREE:-$HOME/dev/oracle-wt/dual-profile-isolation-scaffold}"
CLIENT_HOME="${ORACLE_RR_CLIENT_HOME:-$HOME/.oracle-round-robin}"
ADMISSION_QUEUE_ROOT="$CLIENT_HOME/admission"
CLI="$WORKTREE/dist/bin/oracle-cli.js"
NODE_BIN="${ORACLE_RR_NODE:-$(command -v node || true)}"
CHECK_ONLY=0
DRY_RUN=0
SLUG=""
PROMPT_FILE=""
BUNDLE=""
EXTRA_FILES=()
TUNNEL_PID=""
LOCK_DIR=""
LOCK_OWNED=0
PROD_PID_BEFORE=""
PROD_START_BEFORE=""
TOKEN=""
SSH_OPTIONS=(
	-o BatchMode=yes
	-o ConnectTimeout=5
	-o ConnectionAttempts=1
	-o ServerAliveInterval=5
	-o ServerAliveCountMax=2
)

usage() {
	cat <<'EOF'
Usage:
  run_round_robin.sh --check
  run_round_robin.sh --slug <3-5-word-slug> --prompt-file <path> --bundle <path> [--file <path> ...] [--dry-run]

Runs one browser-mode Pro Extended Oracle consult through the isolated four-slot
staging service on tv. Profile selection is intentionally omitted so the server's
persistent round-robin allocator chooses one of two isolated slots per account.
When all four slots are occupied, the client waits until capacity is available.
EOF
}

fail() {
	printf 'oracle-round-robin: %s\n' "$*" >&2
	exit 1
}

cleanup() {
	local status=$?
	if [[ -n "$TUNNEL_PID" ]] && kill -0 "$TUNNEL_PID" 2>/dev/null; then
		local command_line
		command_line="$(ps -p "$TUNNEL_PID" -o command= 2>/dev/null || true)"
		if [[ "$command_line" == *"-L 127.0.0.1:${LOCAL_FORWARD_PORT}:127.0.0.1:${REMOTE_SERVICE_PORT}"* ]] && [[ "$command_line" == *" ${REMOTE_HOST}"* ]]; then
			kill -TERM "$TUNNEL_PID" 2>/dev/null || true
			wait "$TUNNEL_PID" 2>/dev/null || true
		else
			printf 'oracle-round-robin: refusing to stop unverified tunnel pid %s\n' "$TUNNEL_PID" >&2
		fi
	fi
	if [[ "$LOCK_OWNED" == 1 && -n "$LOCK_DIR" && -f "$LOCK_DIR/pid" ]] && [[ "$(cat "$LOCK_DIR/pid" 2>/dev/null || true)" == "$$" ]]; then
		rm -f "$LOCK_DIR/pid"
		rmdir "$LOCK_DIR" 2>/dev/null || true
	fi
	TOKEN=""
	exit "$status"
}
trap cleanup EXIT INT TERM

while [[ $# -gt 0 ]]; do
	case "$1" in
	--check)
		CHECK_ONLY=1
		shift
		;;
	--dry-run)
		DRY_RUN=1
		shift
		;;
	--slug)
		[[ $# -ge 2 ]] || fail "--slug requires a value"
		SLUG="$2"
		shift 2
		;;
	--prompt-file)
		[[ $# -ge 2 ]] || fail "--prompt-file requires a path"
		PROMPT_FILE="$2"
		shift 2
		;;
	--bundle)
		[[ $# -ge 2 ]] || fail "--bundle requires a path"
		BUNDLE="$2"
		shift 2
		;;
	--file)
		[[ $# -ge 2 ]] || fail "--file requires a path"
		EXTRA_FILES+=("$2")
		shift 2
		;;
	-h | --help)
		usage
		exit 0
		;;
	*) fail "unknown argument: $1" ;;
	esac
done

[[ -n "$NODE_BIN" && -x "$NODE_BIN" ]] || fail "Node.js is unavailable"
[[ "$CHECK_DEADLINE_SECONDS" =~ ^[1-9][0-9]*$ ]] || fail "ORACLE_RR_CHECK_DEADLINE_SECONDS must be a positive integer"
[[ -f "$CLI" ]] || fail "qualified Oracle CLI build is missing: $CLI"
[[ -f "$WORKTREE/dist/src/remote/client.js" ]] || fail "qualified protocol-v2 client build is missing"
[[ -f "$WORKTREE/dist/src/browser/actions/navigation.js" ]] || fail "qualified browser navigation build is missing"

[[ ! -L "$CLIENT_HOME" ]] || fail "isolated client home must not be a symlink: $CLIENT_HOME"
[[ ! -L "$ADMISSION_QUEUE_ROOT" ]] || fail "admission queue root must not be a symlink: $ADMISSION_QUEUE_ROOT"
mkdir -p "$CLIENT_HOME" "$CLIENT_HOME/locks" "$ADMISSION_QUEUE_ROOT"
chmod 700 "$CLIENT_HOME" "$CLIENT_HOME/locks" "$ADMISSION_QUEUE_ROOT"

if [[ "$CHECK_ONLY" == 0 ]]; then
	[[ "$SLUG" =~ ^[a-z0-9]+(-[a-z0-9]+){2,4}$ ]] || fail "slug must contain 3-5 lowercase words separated by hyphens"
	LOCK_DIR="$CLIENT_HOME/locks/$SLUG.lock"
	if ! mkdir "$LOCK_DIR" 2>/dev/null; then
		fail "this session slug is already running; inspect $LOCK_DIR instead of deleting it blindly"
	fi
	LOCK_OWNED=1
	printf '%s\n' "$$" >"$LOCK_DIR/pid"
	chmod 600 "$LOCK_DIR/pid"
fi

local_cli_sha="$(shasum -a 256 "$CLI" | awk '{print $1}')"
local_client_sha="$(shasum -a 256 "$WORKTREE/dist/src/remote/client.js" | awk '{print $1}')"
local_navigation_sha="$(shasum -a 256 "$WORKTREE/dist/src/browser/actions/navigation.js" | awk '{print $1}')"
remote_shas="$(ssh "${SSH_OPTIONS[@]}" "$REMOTE_HOST" "set -eu; R=\"\$HOME/Library/Application Support/OracleStaging/releases/$EXPECTED_BUILD_SHA/src\"; shasum -a 256 \"\$R/dist/bin/oracle-cli.js\" \"\$R/dist/src/remote/client.js\" \"\$R/dist/src/browser/actions/navigation.js\" | cut -d ' ' -f 1")"
remote_cli_sha="$(printf '%s\n' "$remote_shas" | sed -n '1p')"
remote_client_sha="$(printf '%s\n' "$remote_shas" | sed -n '2p')"
remote_navigation_sha="$(printf '%s\n' "$remote_shas" | sed -n '3p')"
[[ "$local_cli_sha" == "$remote_cli_sha" ]] || fail "local CLI does not match qualified green release"
[[ "$local_client_sha" == "$remote_client_sha" ]] || fail "local protocol-v2 client does not match qualified green release"
[[ "$local_navigation_sha" == "$remote_navigation_sha" ]] || fail "local browser navigation build does not match qualified green release"

read -r PROD_PID_BEFORE PROD_START_BEFORE < <(ssh "${SSH_OPTIONS[@]}" "$REMOTE_HOST" 'P=$(lsof -tiTCP:7333 -sTCP:LISTEN | head -1); test -n "$P"; S=$(ps -p "$P" -o lstart= | xargs); printf "%s|%s\n" "$P" "$S"' | awk -F'|' '{print $1, substr($0,index($0,"|")+1)}')

verify_production_identity() {
	local production_after
	production_after="$(ssh "${SSH_OPTIONS[@]}" "$REMOTE_HOST" 'P=$(lsof -tiTCP:7333 -sTCP:LISTEN | head -1); S=$(ps -p "$P" -o lstart= | xargs); printf "%s|%s\n" "$P" "$S"')"
	[[ "$production_after" == "$PROD_PID_BEFORE|$PROD_START_BEFORE" ]] ||
		fail "production Oracle identity changed during the run"
}

ssh "${SSH_OPTIONS[@]}" "$REMOTE_HOST" "EXPECTED_BUILD_SHA='$EXPECTED_BUILD_SHA' CHECK_ONLY='$CHECK_ONLY' CHECK_DEADLINE_SECONDS='$CHECK_DEADLINE_SECONDS' bash -s" <<'REMOTE_CHECK'
set -euo pipefail
G="$HOME/.oracle-staging/dual-profile-green"
LABEL="com.steipete.oracle.staging.dual-profile.green"
launchctl print "gui/$(id -u)/$LABEL" >/dev/null
TOKEN_FILE="$G/secrets/serve.token"
test "$(stat -f %Lp "$TOKEN_FILE")" = "600"
TOKEN=$(cat "$TOKEN_FILE")
curl -fsS --max-time 5 http://127.0.0.1:19474/status >/dev/null
python3 - "$EXPECTED_BUILD_SHA" "$G/config.json" <<'PY'
import json,sys
expected,path=sys.argv[1:]
d=json.load(open(path))["deployment"]
if not d["releaseRoot"].endswith(f"/{expected}/src"): raise SystemExit(1)
if d["service"].get("port") != 19474 or d["service"].get("protocol") != "v2": raise SystemExit(1)
profiles=d["chrome"]["profilePool"]["profiles"]
if [p.get("id") for p in profiles] != [
    "profile-a", "profile-b", "profile-a-2", "profile-b-2"
]: raise SystemExit(1)
if [p.get("cdpPort") for p in profiles] != [19222, 19223, 19224, 19225]: raise SystemExit(1)
PY
if [[ "$CHECK_ONLY" == 1 ]]; then
  deadline=$((SECONDS + CHECK_DEADLINE_SECONDS))
  health_ok=0
  last_error="health endpoint was not checked"
  while (( SECONDS < deadline )); do
    HEALTH=""
    if HEALTH=$(curl -fsS --connect-timeout 2 --max-time 5 -H "Authorization: Bearer $TOKEN" http://127.0.0.1:19474/health); then
      if validation_error=$(python3 - "$EXPECTED_BUILD_SHA" "$HEALTH" 2>&1 <<'PY'
import json,sys
expected=sys.argv[1]
d=json.loads(sys.argv[2])
if d.get("ok") is not True: raise SystemExit("health ok flag is false")
if d.get("buildSha") != expected: raise SystemExit("health build SHA mismatch")
if d.get("pooledMode") is not True or d.get("protocolV2") is not True: raise SystemExit("pooled protocol-v2 mode is unavailable")
capacity=d.get("capacity",{})
active=capacity.get("active")
if capacity.get("maximum") != 4: raise SystemExit("health maximum capacity is not four")
if not isinstance(active, int) or not 0 <= active <= 4: raise SystemExit("health active capacity is invalid")
profiles=d.get("profiles",[])
if [p.get("profileId") for p in profiles] != [
    "profile-a", "profile-b", "profile-a-2", "profile-b-2"
]: raise SystemExit("health profile topology mismatch")
if not all(
    p.get("state") == ("busy" if p.get("activeRun") else "healthy")
    for p in profiles
): raise SystemExit("worker state disagrees with active-run state")
if not all(p.get("available") is (not p.get("activeRun")) for p in profiles): raise SystemExit("worker availability disagrees with active-run state")
if sum(1 for p in profiles if p.get("activeRun")) != active: raise SystemExit("active worker count disagrees with capacity")
PY
      ); then
        health_ok=1
        break
      else
        last_error="$validation_error"
      fi
    else
      last_error="health request failed or exceeded its five-second request deadline"
    fi
    sleep 1
  done
  if [[ "$health_ok" != 1 ]]; then
    printf 'round-robin health preflight failed within %ss: %s\n' "$CHECK_DEADLINE_SECONDS" "$last_error" >&2
    exit 1
  fi
fi
REMOTE_CHECK

TOKEN="$(ssh "${SSH_OPTIONS[@]}" "$REMOTE_HOST" "cat \"\$HOME/$REMOTE_HOME_REL/secrets/serve.token\"")"
[[ "$TOKEN" =~ ^[[:xdigit:]]{64}$ ]] || fail "staging token did not match the expected format"

start_tunnel() {
	local _attempt candidate
	for _attempt in $(seq 1 20); do
		candidate="$(
			python3 - <<'PY'
import socket
with socket.socket() as sock:
    sock.bind(("127.0.0.1", 0))
    print(sock.getsockname()[1])
PY
		)"
		ssh -N "${SSH_OPTIONS[@]}" -o ExitOnForwardFailure=yes \
			-L "127.0.0.1:${candidate}:127.0.0.1:${REMOTE_SERVICE_PORT}" \
			"$REMOTE_HOST" &
		TUNNEL_PID=$!
		sleep 0.2
		if kill -0 "$TUNNEL_PID" 2>/dev/null; then
			LOCAL_FORWARD_PORT="$candidate"
			return 0
		fi
		wait "$TUNNEL_PID" 2>/dev/null || true
		TUNNEL_PID=""
	done
	fail "could not allocate a private local SSH tunnel after 20 attempts"
}

start_tunnel
for _ in $(seq 1 40); do
	kill -0 "$TUNNEL_PID" 2>/dev/null || fail "SSH tunnel exited before becoming ready"
	if curl -fsS --max-time 1 "http://127.0.0.1:${LOCAL_FORWARD_PORT}/status" >/dev/null 2>&1; then
		break
	fi
	sleep 0.25
done
curl -fsS --max-time 2 "http://127.0.0.1:${LOCAL_FORWARD_PORT}/status" >/dev/null || fail "SSH tunnel did not become ready"
TOKEN="$TOKEN" python3 - "$LOCAL_FORWARD_PORT" <<'PY'
import json, os, sys, urllib.error, urllib.request
port=sys.argv[1]
req=urllib.request.Request(
    f"http://127.0.0.1:{port}/runs",
    headers={"Authorization": "Bearer " + os.environ["TOKEN"]},
)
try:
    urllib.request.urlopen(req, timeout=3)
except urllib.error.HTTPError as error:
    body=json.loads(error.read())
    assert error.code == 404 and body.get("error") == "unsupported_protocol"
else:
    raise AssertionError("protocol v1 unexpectedly accepted")
PY

if [[ "$CHECK_ONLY" == 1 ]]; then
	verify_production_identity
	printf 'round_robin_check=ok build=%s slots=4 capacity_wait=enabled v1=disabled production_pid=%s\n' "$EXPECTED_BUILD_SHA" "$PROD_PID_BEFORE"
	exit 0
fi

[[ -f "$PROMPT_FILE" && -s "$PROMPT_FILE" ]] || fail "prompt file is missing or empty: $PROMPT_FILE"
[[ -f "$BUNDLE" && -s "$BUNDLE" ]] || fail "bundle is missing or empty: $BUNDLE"
for file in "${EXTRA_FILES[@]}"; do [[ -f "$file" ]] || fail "extra file is missing: $file"; done
if [[ -e "$CLIENT_HOME/sessions/$SLUG" ]]; then
	ORACLE_HOME_DIR="$CLIENT_HOME" \
		ORACLE_ENGINE="browser" \
		ORACLE_REMOTE_HOST="127.0.0.1:${LOCAL_FORWARD_PORT}" \
		ORACLE_REMOTE_TOKEN="$TOKEN" \
		"$NODE_BIN" "$CLI" session "$SLUG"
	verify_production_identity
	META="$CLIENT_HOME/sessions/$SLUG/meta.json"
	[[ -f "$META" ]] || fail "session receipt is missing: $META"
	python3 - "$META" <<'PY'
import json,sys
p=sys.argv[1]
d=json.load(open(p))
r=d.get("remoteRouting") or {}
profile=r.get("assignedProfileId")
assert profile in {"profile-a","profile-b","profile-a-2","profile-b-2"}, "missing round-robin slot receipt"
assert r.get("protocolVersion") == 2
print(f"round_robin_profile={profile}")
print(f"session_receipt={p}")
PY
	exit 0
fi

prompt="$(cat "$PROMPT_FILE")"
args=(
	"$CLI"
	--engine browser
	--model gpt-5.6-pro
	--browser-thinking-time extended
	--browser-attachments always
	--timeout auto
	--heartbeat 30
	--slug "$SLUG"
	--prompt "$prompt"
	--file "$BUNDLE"
)
for file in "${EXTRA_FILES[@]}"; do args+=(--file "$file"); done
if [[ "$DRY_RUN" == 1 ]]; then args+=(--dry-run summary); fi

ORACLE_REMOTE_ADMISSION_QUEUE_NAMESPACE="$ADMISSION_QUEUE_NAMESPACE" \
	ORACLE_REMOTE_ADMISSION_QUEUE_ROOT_DIR="$ADMISSION_QUEUE_ROOT" \
	ORACLE_HOME_DIR="$CLIENT_HOME" \
	ORACLE_ENGINE="browser" \
	ORACLE_REMOTE_HOST="127.0.0.1:${LOCAL_FORWARD_PORT}" \
	ORACLE_REMOTE_TOKEN="$TOKEN" \
	"$NODE_BIN" "${args[@]}"

verify_production_identity

if [[ "$DRY_RUN" == 0 ]]; then
	META="$CLIENT_HOME/sessions/$SLUG/meta.json"
	[[ -f "$META" ]] || fail "session receipt is missing: $META"
	python3 - "$META" <<'PY'
import json,sys
p=sys.argv[1]
d=json.load(open(p))
r=d.get("remoteRouting") or {}
profile=r.get("assignedProfileId")
assert profile in {"profile-a","profile-b","profile-a-2","profile-b-2"}, "missing round-robin slot receipt"
assert r.get("protocolVersion") == 2
print(f"round_robin_profile={profile}")
print(f"session_receipt={p}")
PY
fi
