#!/usr/bin/env bash
# Wrapper-layer remote-seat shim. Sourced by a WRAPPER-CONTRACT wrapper AFTER its own arg
# validation and inspection modes, so bad args still fail locally with exit 2 and --health /
# --list-models never pay an ssh round-trip.
#
# seat_remote_dispatch returns 1 when this adapter is not remoted — the wrapper then continues
# down its normal local path unchanged. When it IS remoted the function never returns: it exits
# with the launcher's rc, which is the wrapper's rc.
#
# Launcher rc 70 also means "run it here": remoting is switched off in build-remote.json for this
# repo. A broken or busy buildbox is rc 3, never a fallback onto the workstation.
#
# Enable/disable is CONFIG (modules/harness/seat/seat-remote.json), never an env the
# orchestrator must set. HARNESS_SEAT_REMOTE=0 is a kill switch back to local.
#
# Account provenance: only adapters that select credentials via --profile (codex) may journal
# account. ca/grok/na ignore --profile — never claim seat role or an ignored profile as account.

seat_remote_dispatch() {
  local adapter="$1" wrapper_file="$2" workspace="$3" prompt="$4" slug="$5" model="$6" timeout="$7" profile="$8" cont_flag="${9:-}" cont_id="${10:-}"

  [[ "${HARNESS_SEAT_CONTAINER:-}" == "1" ]] && return 1

  local seat_dir launcher
  seat_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../seat" 2>/dev/null && pwd)" || return 1
  launcher="$seat_dir/remote-seat.mjs"
  [[ -f "$launcher" ]] || return 1
  command -v node >/dev/null 2>&1 || return 1

  node "$launcher" --check "$adapter" || return 1

  local seat="${HARNESS_SEAT:-$adapter}"
  local account=""
  if [[ "$adapter" == "codex" && -n "$profile" ]]; then
    account="$profile"
  fi
  if [[ -n "$account" ]]; then
    printf '%s\n' "{\"kind\":\"seat.remote\",\"seat\":\"$seat\",\"account\":\"$account\",\"adapter\":\"$adapter\"}" >&2
  else
    printf '%s\n' "{\"kind\":\"seat.remote\",\"seat\":\"$seat\",\"adapter\":\"$adapter\"}" >&2
  fi

  local args=(--adapter "$adapter" --wrapper "$wrapper_file" --workspace "$workspace" --trust "$prompt" --task-slug "$slug")
  [[ -n "$model" ]]   && args+=(--model "$model")
  [[ -n "$timeout" ]] && args+=(--timeout "$timeout")
  if [[ "$adapter" == "codex" && -n "$profile" ]]; then
    args+=(--profile "$profile")
  fi
  [[ -n "$cont_flag" && -n "$cont_id" ]] && args+=("$cont_flag" "$cont_id")

  node "$launcher" "${args[@]}"
  local rc=$?
  [[ $rc -eq 70 ]] && return 1
  exit $rc
}
