import { spawn, spawnSync } from 'node:child_process'
import fs from 'node:fs'
import http from 'node:http'
import https from 'node:https'
import net from 'node:net'
import os from 'node:os'
import path from 'node:path'
import { compareSemver } from '@contrast/runtime-delivery'
import { WebSocket } from 'ws'
import { formatLockOwner } from '../../../peach-kit/src/agent-identity'
import { buildPermissionSeedScript } from '../../detox/launch-permissions'
import { ANDROID_ROOT_MODULE_QUERY_PARAM } from '../../src/androidRootModuleContract'
import { loadRNXAppConfig } from '../../src/app-config'
import { isAppDeepLinkTarget, openAppUrl } from '../../src/app-url'
import { isLoopbackHost } from '../../src/backend-origin'
import { ensureCliCompanion, getCliRuntime } from '../../src/cli-runtime.ts'
import { getCliVersion } from '../../src/cli-version'
import {
  applyPeachConfigToUrl,
  mergePeachConfig,
  readNativeRenderer,
  readPeachConfigFromSearchParams,
  type PeachConfig,
} from '../../src/config'
import {
  desktopHostDelivery,
  desktopHostPlatform,
  headlessHostCommand,
} from '../../src/desktop-host-delivery'
import { type ResolvedDevBundle } from '../../src/dev-bundle-resolution'
import { isDeviceModel, type DeviceModel } from '../../src/device-catalog.ts'
import { readProjectDotEnv } from '../../src/dot-env'
import { awaitStampedExpoSwiftReady } from '../../src/expo-swift-ready'
import { flowTimeoutScale } from '../../src/flow-timeout-scale'
import { activatePeachHome } from '../../src/home-activity'
import {
  isDaemonLockfileFresh,
  isDevBridgeLockfileFresh,
  isSootsimDevCheckout,
  PEACH_HOME_ENV,
  readActiveRuntime,
  readDaemonLockfile,
  readDevBridgeLockfiles,
  readLiveRuntimeVersions,
  readSimulatorDriverPreference,
  rnxHomeDir,
  runtimeDir,
  runtimesDir,
} from '../../src/home-paths'
import { stageHostBytes } from '../../src/host/staged-host-files'
import { LAUNCH_METADATA_QUERY_PARAM } from '../../src/launchMetadataContract'
import { detectBundleModeFromText } from '../../src/metro-production-bundle'
import { applyHotMode } from '../../src/native-dev-bundle-url'
import { isProcessRunning } from '../../src/process-liveness'
import { ensureProfile } from '../../src/profiles'
import {
  resolveDevCheckoutRuntimeAssetRoot,
  resolveDevCheckoutRuntimeRoot,
  runtimeVersionHostname,
} from '../../src/runtime-assets'
import { rnxRuntime } from '../../src/runtime-delivery'
import { sleep } from '../../src/sleep'
import { findExpoAppConfig } from '../app-project'
import { discoverOneNativeAppSplash } from '../app-splash'
import { extractAppBinaryBundle, isAppBinaryPath } from '../binary-sidecar'
import { printBridgeFailureDiagnostics } from '../bridge-diagnostics'
import {
  assertNoPendingOpen,
  clearCurrentSimId,
  markOpenPending,
  getStableOwnerPid,
  saveAgentId,
  readCurrentSimId,
  saveCurrentSimId,
} from '../current-sim'
import { findDesktopCompanion, nativeDesktopIsDefault } from '../desktop-companion'
import { validateDeviceOption } from '../device-option'
import { getDriver } from '../drivers/registry'
import { isTeamMachineSession, openUrl as openUrlInBrowser } from '../open-url'
import { redactConfigurationForDiagnostics } from '../output-redaction'
import { GLOBAL_FLAG_TAKES_VALUE } from '../parse-args'
import { diagnosticsAllowedForCurrentProcess, isCi } from '../privacy'
import { rethrowIfExit, peachExit } from '../run-rnx'
import { collectRuntimeDiagnostics } from '../runtime-diagnostics'
import { rnxSelfInvocation } from '../self-invocation'
import { accent, muted, warning } from '../ui'
import {
  BRIDGE_VALUE_FLAGS,
  BridgeSimLockedError,
  createBridge,
  isLiveBridge,
  callInBridgeWrite,
  createBridgeFromParsed,
  parseBridgeCliArgs,
  printBridgeWorldNotice,
  resolveBridgePortForPin,
  worldForBridgePort,
  type BridgeSimInfo,
  type ParsedBridgeCliArgs,
  type WsBridge,
} from '../ws-bridge'
import { getDaemonServiceStatus, retireIdleBridge } from './daemon'
import { inspectDescribe, inspectReadySnapshot, waitReadyReason } from './inspect/core'
import { waitForSimReady } from './inspect/shared'
import { runInstallDesktop } from './install-desktop'
import {
  buildShellUrl,
  looksLikeShellPathTarget,
  looksLikeSootsimUrl,
  resolveAppProjectForBundleUrl,
  resolveConnectionInputForCli,
  resolveShellBaseUrlForBridgePort,
  shellUrlPlatform,
  shouldResolveBundleTargetInCli,
  startExpoConfigRead,
  type BuildShellUrlOptions,
} from './shell-url'
import { hasInstalledPeachSkills } from './skills'
import type { DriverId, DriverLaunchResult } from '../drivers/types'
import type { SystemPermissionBootSeed } from '@peach/globals'

interface ControlCommandOptions {
  port?: number
  timeoutMs?: number
  runtimeConfig?: PeachConfig
}

export interface OpenCommandResources {
  // the launch permissions were deposited ahead of the opened app's boot
  launchPermissionsSeeded?: boolean
  bridge?: ReturnType<typeof spawn>
  bridgeReady?: boolean
  port?: number
  driver?: DriverLaunchResult & { driverId: DriverId }
  simId?: string
}

interface DriverConnectWaitOptions {
  attempts: number
  intervalMs: number
  timeoutMs: number
  hostTimeoutMs: number
}

const DEFAULT_DRIVER_CONNECT_TIMEOUT_MS = 120_000
const DRIVER_CONNECT_INTERVAL_MS = 100
const DRIVER_CONNECT_HOST_GRACE_MS = 5_000
// ceiling for a bridge that is alive but never becomes ready. a bridge that
// exits fails at once and a slow one is judged by its own lockfile and
// handshake, so this is not the expected startup time.
const OPEN_BRIDGE_SPAWN_TIMEOUT_MS = 60_000
const OPEN_BRIDGE_RUNTIME_TIMEOUT_MS = 600_000
const OPEN_BRIDGE_HEALTH_TIMEOUT_MS = 10_000
const OPEN_BRIDGE_SILENCE_MS = 30_000
// a closed port refuses at once, so this window only matters when something
// listens: a live bridge on a loaded machine can take longer than 250 ms to
// finish the handshake, and missing it spawned a second bridge or reported a
// live daemon as unreachable.
const LIVE_BRIDGE_HANDSHAKE_TIMEOUT_MS = 2_000

function parsePositiveIntegerEnv(name: string): number | null {
  const value = process.env[name]?.trim()
  if (!value) return null
  const parsed = Number(value)
  return Number.isInteger(parsed) && parsed > 0 ? parsed : null
}

export function resolveDriverConnectWaitOptions(): DriverConnectWaitOptions {
  const timeoutMs =
    parsePositiveIntegerEnv('SOOTSIM_DRIVER_CONNECT_TIMEOUT_MS') ??
    parsePositiveIntegerEnv('SOOTSIM_PW_CONNECT_TIMEOUT_MS') ??
    DEFAULT_DRIVER_CONNECT_TIMEOUT_MS
  return {
    timeoutMs,
    hostTimeoutMs: timeoutMs + DRIVER_CONNECT_HOST_GRACE_MS,
    intervalMs: DRIVER_CONNECT_INTERVAL_MS,
    attempts: Math.max(1, Math.ceil(timeoutMs / DRIVER_CONNECT_INTERVAL_MS)),
  }
}

function isDriverId(value: string): value is DriverId {
  return value === 'desktop' || value === 'electron' || value === 'playwright'
}

function simUsesDriver(
  sim: BridgeSimInfo,
  driverId: DriverId,
  renderer?: 'chromium' | 'native',
  hostExecutable?: string | null,
): boolean {
  if (driverId === 'playwright') {
    return (
      sim.meta?.sootsimHostDriver === 'playwright' &&
      (!renderer || sim.meta?.peachRenderer === renderer) &&
      (hostExecutable === undefined ||
        (hostExecutable !== null && sim.meta?.peachHostExecutable === hostExecutable))
    )
  }
  if (driverId === 'desktop') {
    return Boolean(
      sim.url && new URL(sim.url).searchParams.get('peachHostDriver') === 'desktop',
    )
  }
  return sim.userAgent?.includes('Electron/') === true
}

// resolve headless for a driver launch. explicit flags always win
// (--headless → true, --headed → false). otherwise: a headed default
// on mac/windows for humans; tm sessions default headless. on linux with no DISPLAY/WAYLAND_DISPLAY there is no
// X server, so the playwright driver auto-flips to headless with a
// single-line note. electron ignores headless mode, so it defaults false.
export function resolveDriverHeadless(args: string[], driverId: string): boolean {
  if (args.includes('--headless')) return true
  if (args.includes('--headed')) return false
  if (driverId === 'playwright' && isTeamMachineSession()) return true
  if (
    driverId === 'playwright' &&
    process.platform === 'linux' &&
    !process.env.DISPLAY &&
    !process.env.WAYLAND_DISPLAY
  ) {
    console.error(
      '  no display detected → running playwright headless (override with --headed)',
    )
    return true
  }
  return false
}

type BridgeOpenGate = {
  newShell: boolean
  simId?: string
  simIdSource?: 'flag' | 'saved' | 'none'
  driverId?: DriverId
  renderer?: 'chromium' | 'native'
  pinnedHostExecutable?: string | null
}

export async function ensureBridgeForOpen(
  preferredPort: number,
  explicitPort = false,
  resources?: OpenCommandResources,
  runtimeSource: 'bridge' | 'external' = 'bridge',
  gate: BridgeOpenGate = { newShell: true },
): Promise<number> {
  const port = await connectBridgeForOpen(
    preferredPort,
    explicitPort,
    resources,
    runtimeSource,
  )
  // a bridge accepts connections while its first runtime download is still
  // running, and a shell page served by that bridge answers 503 until the
  // runtime directory exists. a registered page is not that runtime: --new
  // would hand the driver the 503 url. skip the wait only when this open
  // will reuse a page whose origin already answers. a new shell waits until
  // the bridge install settles or the shell itself answers, and does not
  // start a second install over the one already in flight.
  if (runtimeSource === 'bridge') {
    const reusingReadyOrigin =
      !gate.newShell && (await provenReadyReuseOrigin(port, gate))
    if (!reusingReadyOrigin) {
      const readiness = await waitForBridgeRuntime(port)
      if (readiness === 'settled') await ensureRuntimeForOpen()
    }
  }
  return port
}

async function provenReadyReuseOrigin(
  port: number,
  gate: BridgeOpenGate,
): Promise<boolean> {
  if (!gate.driverId || !gate.simId || gate.simIdSource === 'none' || !gate.simIdSource) {
    return false
  }
  const bridge = createBridge(port, { commandTimeoutMs: 2_000 })
  try {
    const sims = await bridge.listSims()
    const sim = sims.find((candidate) => candidate.id === gate.simId)
    if (!sim?.url || sim.readyState !== 'open') return false
    if (
      !simUsesDriver(
        sim,
        gate.driverId,
        gate.renderer,
        gate.pinnedHostExecutable ?? undefined,
      )
    ) {
      return false
    }
    return await originServesShell(sim.url)
  } catch {
    return false
  } finally {
    bridge.close()
  }
}

async function originServesShell(pageOrOrigin: string): Promise<boolean> {
  try {
    const origin = new URL(pageOrOrigin).origin
    const res = await fetch(origin, { signal: AbortSignal.timeout(2_000) })
    return res.status !== 503
  } catch {
    return false
  }
}

// the install runs inside the bridge and reports completion through
// /healthz. a bridge that answers is installing, so only a bridge that is gone
// (connection refused) or silent for a while fails the wait; the ceiling only
// bounds an install that never finishes.
function portRefusesConnections(port: number): Promise<boolean> {
  return new Promise((resolve) => {
    let refused = false
    const socket = net.connect(port, '127.0.0.1')
    socket.setTimeout(OPEN_BRIDGE_HEALTH_TIMEOUT_MS, () => socket.destroy())
    socket.once('connect', () => socket.destroy())
    socket.once('close', () => resolve(refused))
    socket.once('error', (err: NodeJS.ErrnoException) => {
      refused = err.code === 'ECONNREFUSED'
    })
  })
}

async function waitForBridgeRuntime(port: number): Promise<'settled' | 'serving'> {
  const deadline = Date.now() + OPEN_BRIDGE_RUNTIME_TIMEOUT_MS
  let lastAnswerAt = Date.now()
  while (Date.now() < deadline) {
    try {
      const res = await fetch(`http://127.0.0.1:${port}/healthz`, {
        signal: AbortSignal.timeout(OPEN_BRIDGE_HEALTH_TIMEOUT_MS),
      })
      const health = (await res.json()) as { bootstrapping?: boolean }
      if (!health.bootstrapping) return 'settled'
      lastAnswerAt = Date.now()
      // the install flag can stay true after the shell directory is already
      // being served. a new page can use that origin, and installing again
      // would race the download still in flight.
      if (await originServesShell(`http://127.0.0.1:${port}/`)) return 'serving'
    } catch {
      if (await portRefusesConnections(port)) {
        throw new Error(
          `peach bridge on port ${port} exited while installing its runtime`,
        )
      }
      if (Date.now() - lastAnswerAt > OPEN_BRIDGE_SILENCE_MS) {
        throw new Error(
          `peach bridge on port ${port} stopped answering for ${Math.round(OPEN_BRIDGE_SILENCE_MS / 1000)}s while installing its runtime`,
        )
      }
    }
    await sleep(150)
  }
  throw new Error(
    `peach bridge on port ${port} did not finish installing its runtime within ${Math.round(OPEN_BRIDGE_RUNTIME_TIMEOUT_MS / 1000)}s`,
  )
}

async function connectBridgeForOpen(
  preferredPort: number,
  explicitPort: boolean,
  resources: OpenCommandResources | undefined,
  runtimeSource: 'bridge' | 'external',
): Promise<number> {
  isolateHomeForExplicitPort(preferredPort, explicitPort, readDaemonLockfile())
  await retireOutdatedIdleBridge(readDaemonLockfile())
  const lock = readDaemonLockfile()
  const preferredWorld = worldForBridgePort(preferredPort)
  const handshakeTimeoutMs = LIVE_BRIDGE_HANDSHAKE_TIMEOUT_MS * flowTimeoutScale()
  const handshake = await bridgeHandshake(preferredPort, handshakeTimeoutMs)
  if ((explicitPort || preferredWorld !== null) && handshake === 'open') {
    return preferredPort
  }
  if (explicitPort && preferredWorld !== null) {
    throw new Error(
      unreachableBridgeMessage(preferredPort, handshake, handshakeTimeoutMs),
    )
  }
  if (
    !explicitPort &&
    lock &&
    isDaemonLockfileFresh(lock) &&
    (lock.bridgePort === preferredPort
      ? handshake === 'open'
      : await canConnectToBridge(lock.bridgePort, handshakeTimeoutMs))
  ) {
    return lock.bridgePort
  }
  if (lock && isDaemonLockfileFresh(lock)) {
    throw new Error(
      `peach bridge lockfile is fresh (port ${lock.bridgePort}) but the bridge is not reachable. run \`peach daemon restart\` or \`peach daemon uninstall\`.`,
    )
  }

  // starting a bridge needs ready local assets; an existing bridge gets
  // to finish its own install before the caller validates them.
  if (runtimeSource === 'bridge') await ensureRuntimeForOpen()
  // the background service keeps a bridge warm; without it every cold open
  // starts one here, so say once why this open is slower.
  const service = getDaemonServiceStatus()
  if (service.supported && !service.installed && !isCi()) {
    console.error(
      `  ${warning('!')} ${muted('the background service is off, so Peach starts slower; turn it on with')} ${accent('peach daemon install')}`,
    )
  }
  const { executable, prefixArgs } = rnxSelfInvocation()
  // the bridge outlives open, so it must not hold the command's captured stderr.
  const bridgeLogPath = path.join(
    os.tmpdir(),
    `peach-bridge-${Date.now()}-${process.pid}.log`,
  )
  const bridgeLogFd = fs.openSync(bridgeLogPath, 'a')
  let child: ReturnType<typeof spawn>
  try {
    child = spawn(
      executable,
      [...prefixArgs, 'serve', '--quiet', '--port', String(preferredPort)],
      {
        detached: true,
        stdio: ['ignore', 'ignore', bridgeLogFd],
        // this bridge does not supply the shell, so it needs no runtime updates.
        env:
          runtimeSource === 'external'
            ? { ...process.env, PEACH_UPDATE_CHECK: 'off' }
            : process.env,
      },
    )
  } finally {
    fs.closeSync(bridgeLogFd)
  }
  if (resources) {
    resources.bridge = child
    resources.port = preferredPort
  }
  let childExit: string | null = null
  const exited = new AbortController()
  child.once('exit', (code, signal) => {
    childExit = String(code ?? signal ?? 'unknown')
    exited.abort()
  })
  child.unref()

  const deadline = Date.now() + OPEN_BRIDGE_SPAWN_TIMEOUT_MS
  while (Date.now() < deadline) {
    const nextLock = readDaemonLockfile()
    if (
      explicitPort &&
      nextLock &&
      isDaemonLockfileFresh(nextLock) &&
      nextLock.bridgePort !== preferredPort
    ) {
      // serve fell back because something already holds the pinned port. the
      // bridge it started is one nobody asked for: stop it, and use the pinned
      // port if what holds it is a bridge that answers given longer.
      child.kill()
      if (await canConnectToBridge(preferredPort, 5_000)) return preferredPort
      throw new Error(
        `peach open: requested bridge port ${preferredPort} is held by a process that does not answer as a peach bridge.`,
      )
    }
    const selectedPort = explicitPort ? preferredPort : nextLock?.bridgePort
    // ready is the spawned bridge's own lockfile plus a completed handshake. a
    // loaded machine needs the full handshake budget, not a 250ms probe.
    if (
      nextLock &&
      nextLock.pid === child.pid &&
      isDaemonLockfileFresh(nextLock) &&
      selectedPort !== undefined &&
      (await canConnectToBridge(
        selectedPort,
        Math.max(1, Math.min(handshakeTimeoutMs, deadline - Date.now())),
        exited.signal,
      ))
    ) {
      console.error(
        `  Started a local bridge on port ${selectedPort}. Run \`peach daemon install\` to keep it ready between commands.`,
      )
      if (resources) {
        resources.bridgeReady = true
        resources.port = selectedPort
      }
      return selectedPort
    }
    if (childExit) break
    await sleep(Math.max(0, Math.min(150, deadline - Date.now())))
  }

  const reason = childExit
    ? `peach bridge exited before becoming ready (exit ${childExit})`
    : `peach bridge did not start within ${Math.round(OPEN_BRIDGE_SPAWN_TIMEOUT_MS / 1000)}s`
  const bridgeLog = fs.readFileSync(bridgeLogPath, 'utf8').trim().slice(-2000)
  throw new Error(
    `${reason}${bridgeLog ? `\n${bridgeLog}` : ''}\nbridge log: ${bridgeLogPath}`,
  )
}

// a bridge started by an older cli lacks the routes this cli's sims need, and
// they sit reconnecting against it. replace it once nothing uses it: no live or
// retained sim, and not the Mac app's own bridge. a busy or unanswering bridge
// is left alone, so active sessions are never cut.
async function retireOutdatedIdleBridge(
  lock: ReturnType<typeof readDaemonLockfile>,
): Promise<void> {
  if (!lock || !isDaemonLockfileFresh(lock) || lock.bootstrapping) return
  const current = getCliVersion()
  if (isSootsimDevCheckout() || lock.cliVersion === current) return
  if (lock.cliVersion && compareSemver(current, lock.cliVersion) <= 0) return
  const appRecord = path.join(rnxHomeDir(), 'app-runtime.json')
  if (fs.existsSync(appRecord)) return
  const bridge = createBridge(lock.bridgePort, { commandTimeoutMs: 2000 })
  const simCount = await bridge.listSims({ includeRetained: true }).then(
    (sims) => sims.length,
    () => -1,
  )
  bridge.close()
  if (simCount !== 0) return
  console.error(
    `  Replacing the idle peach bridge on port ${lock.bridgePort} (${lock.cliVersion ? `v${lock.cliVersion}` : 'older'}) with v${current}.`,
  )
  await retireIdleBridge(lock)
  const deadline = Date.now() + 10_000
  while (isDaemonLockfileFresh(readDaemonLockfile()) && Date.now() < deadline)
    await sleep(100)
}

// one bridge per peach home, so an explicit port the active daemon does not own
// gets its own home: this command and the bridge it starts both run in it,
// sharing the daemon's installed runtimes unless this CLI serves its own dev
// build.
function isolateHomeForExplicitPort(
  preferredPort: number,
  explicitPort: boolean,
  lock: ReturnType<typeof readDaemonLockfile>,
): void {
  if (
    !explicitPort ||
    !lock ||
    !isDaemonLockfileFresh(lock) ||
    lock.bridgePort === preferredPort
  ) {
    return
  }
  if (
    readDevBridgeLockfiles().some(
      (devBridge) =>
        devBridge.bridgePort === preferredPort && isDevBridgeLockfileFresh(devBridge),
    )
  ) {
    return
  }
  const sharedRuntimes = runtimesDir()
  const home = path.join(rnxHomeDir(), 'port-homes', String(preferredPort))
  activatePeachHome(home)
  const runtimes = path.join(home, 'runtimes')
  // a dev checkout serves its own build (ensureRuntimeForOpen returns early
  // for it): linking the ambient installed runtimes here would make the
  // explicit-home + active-runtime check in resolveDevCheckoutRuntimeAssetRoot
  // flip this CLI and the bridge it spawns into installed-runtime replay,
  // shadowing the dev build with older published bytes the dev companion is
  // not in. read the mode before PEACH_HOME is set, so a deliberately staged
  // home (explicit home + active runtime) still shares its runtimes, as does
  // an installed CLI with no dev build.
  if (resolveDevCheckoutRuntimeRoot()) {
    removePortHomeSharedRuntimesLink(runtimes, sharedRuntimes)
  } else if (fs.existsSync(sharedRuntimes) && !fs.existsSync(runtimes)) {
    fs.symlinkSync(sharedRuntimes, runtimes)
  }
  process.env[PEACH_HOME_ENV] = home
}

// drop the shared-runtimes symlink this isolation created on an earlier run,
// so a port home staged before the dev-checkout share fix serves the dev
// build again. only the exact link to the ambient runtimes goes: a real
// directory means runtimes were deliberately staged in this port home.
function removePortHomeSharedRuntimesLink(
  runtimes: string,
  sharedRuntimes: string,
): void {
  let stat: fs.Stats
  try {
    stat = fs.lstatSync(runtimes)
  } catch {
    return
  }
  if (!stat.isSymbolicLink()) return
  let target: string
  try {
    target = path.resolve(path.dirname(runtimes), fs.readlinkSync(runtimes))
  } catch {
    return
  }
  if (target === sharedRuntimes) fs.unlinkSync(runtimes)
}

export async function ensureRuntimeForOpen() {
  // a dev checkout serves its own build; staging a published runtime into an
  // isolated home would make the daemon serve that instead.
  if (resolveDevCheckoutRuntimeRoot()) return
  // a checkout with no engine build serves the installed runtime, whose engine
  // predates this checkout's launch metadata and Swift output, so say so before
  // its failures read like app bugs.
  if (resolveDevCheckoutRuntimeAssetRoot()) {
    console.error(
      `  this checkout has no engine build, so the installed runtime serves it; run \`bun run build:peach\` to test this checkout's engine`,
    )
  }
  const active = readActiveRuntime()
  if (active && fs.existsSync(path.join(runtimeDir(active), 'index.html'))) {
    await ensureCliCompanion(runtimeDir(active))
    return
  }
  // a populated home without a ready active runtime may still be staging.
  // only an empty home can safely opt into the published runtime.
  const directory = runtimesDir()
  if (fs.existsSync(directory) && fs.readdirSync(directory).length > 0) {
    throw new Error(
      'peach open: runtime staging or selection is incomplete. finish staging and select the runtime with peach runtime use <version> before opening.',
    )
  }
  console.error('  installing peach engine runtime...')
  const { runRuntime } = await import('./runtime')
  await runRuntime(['install'], {})
}

// 'foreign' is a server that accepts the websocket but whose /healthz does not
// identify a peach bridge: another tool holding the port, never adopted.
type BridgeHandshake = 'open' | 'refused' | 'timeout' | 'foreign'

function bridgeHandshake(
  port: number,
  timeoutMs: number,
  signal?: AbortSignal,
): Promise<BridgeHandshake> {
  return new Promise((resolve) => {
    const ws = new WebSocket(`ws://127.0.0.1:${port}`, { handshakeTimeout: timeoutMs })
    let settled = false
    const finish = (result: BridgeHandshake) => {
      if (settled) return
      settled = true
      clearTimeout(timer)
      signal?.removeEventListener('abort', onAbort)
      if (ws.readyState === WebSocket.OPEN) ws.close()
      else if (ws.readyState === WebSocket.CONNECTING) ws.terminate()
      resolve(result)
    }
    const timer = setTimeout(() => finish('timeout'), timeoutMs)
    const onAbort = () => finish('timeout')
    if (signal?.aborted) onAbort()
    else signal?.addEventListener('abort', onAbort)
    ws.once('open', () => {
      fetch(`http://127.0.0.1:${port}/healthz`, {
        signal: AbortSignal.timeout(timeoutMs),
      })
        .then((res) => res.json())
        .then(
          (health: unknown) =>
            finish(
              health && typeof health === 'object' && Reflect.get(health, 'ok') === true
                ? 'open'
                : 'foreign',
            ),
          () => finish('foreign'),
        )
    })
    ws.on('error', (err: NodeJS.ErrnoException) => {
      finish(
        err.code === 'ECONNREFUSED' || err.code === 'ENOTFOUND' ? 'refused' : 'timeout',
      )
    })
  })
}

function unreachableBridgeMessage(
  port: number,
  handshake: BridgeHandshake,
  timeoutMs: number,
): string {
  if (handshake === 'foreign') {
    return `peach open: requested bridge port ${port} is held by another program, not a peach bridge. stop it or pass a free port with --port <port>.`
  }
  if (handshake === 'timeout') {
    const cores = Math.max(1, os.cpus().length)
    const load = os.loadavg()[0]
    if (load >= cores) {
      return `peach open: requested bridge port ${port} did not finish its handshake within ${timeoutMs / 1000}s while load average was ${load.toFixed(1)} on ${cores} cores.`
    }
  }
  return `peach open: requested bridge port ${port} is not reachable.`
}

function canConnectToBridge(
  port: number,
  timeoutMs: number,
  signal?: AbortSignal,
): Promise<boolean> {
  return bridgeHandshake(port, timeoutMs, signal).then((result) => result === 'open')
}

// peach share/preview/build links (e.g. https://peachsim.com/preview/<id>,
// https://contrast.dev/build/<owner>/<repo>/<branch>) are full player pages
// served by the Contrast app — NOT Metro bundles and NOT driveable shell sims.
// passing one to `peach open` used to fall through to the bundle resolver,
// which fetched the HTML page and choked with "Unexpected token '<'". two
// hard reasons they can't become a CLI-driveable sim:
//   1. the engine only attaches to the local CLI bridge from a localhost /
//      127.0.0.1 origin (see engine `mcp/ws-bridge.ts` connect gate), so a
//      remote preview page never registers a sim.
//   2. a captured share's transformed bundle is pinned to the engine build
//      that produced it — its lazy `/engine-tenant/assets/*` chunk hashes
//      only exist on that deploy, so a remote share can't be re-hosted
//      through the local dev shell (the dynamic chunk import 404s).
// recognize these URLs so `open` opens them for viewing instead.
function looksLikeSootSimShareUrl(target: string): boolean {
  try {
    const pathname = new URL(target).pathname.replace(/\/+$/, '') || '/'
    return /^\/preview\/[^/]+$/.test(pathname) || /^\/build\/.+/.test(pathname)
  } catch {
    return false
  }
}

// a dev server builds an app's graph on the first request for its bundle and
// finishes the build after that request goes away. `peach open` asks as soon as
// the bundle is resolved, so the build overlaps bridge, host and runtime boot;
// the engine's own request for the same url then joins it, so the cli drops its
// copy unread. nothing the open stamps asks the dev server, so a busy build
// cannot change the page. the socket is unreferenced: a pending build never
// holds the command open.
function startDevServerBuild(bundleUrl: string): void {
  const request = (bundleUrl.startsWith('https:') ? https : http).get(
    bundleUrl,
    (response) => response.resume(),
  )
  request.on('socket', (socket) => socket.unref())
  request.on('error', () => {})
}

async function readSimDevice(bridge: WsBridge, simId: string): Promise<string | null> {
  try {
    const sim = (await bridge.listSims()).find((candidate) => candidate.id === simId)
    return sim?.url ? new URL(sim.url).searchParams.get('device') : null
  } finally {
    bridge.close()
  }
}

// a built bundle on disk (`peach open ./dist/ios.js`). the bridge serves a
// staged copy, so it loads with no dev server running.
function prebuiltBundleFile(target: string): string | null {
  if (!/\.(js|bundle|jsbundle)$/i.test(target)) return null
  const file = path.resolve(process.cwd(), target)
  return fs.statSync(file, { throwIfNoEntry: false })?.isFile() ? file : null
}

// the url names the bundle's own mode, so the engine boots the matching
// tenant first instead of restarting into it after the fetch.
export async function stagePrebuiltBundle(
  file: string,
  bridgePort: number,
  prepareSource?: (source: string) => Promise<string>,
): Promise<ResolvedDevBundle> {
  const bytes = fs.readFileSync(file)
  const source = bytes.toString('utf8')
  const mode = await detectBundleModeFromText(source)
  if (!mode) {
    throw new Error(
      `${file} carries no __DEV__ prelude or Metro module shape, so its development or production build cannot be told apart`,
    )
  }
  const prepared = prepareSource
    ? await prepareSource(source)
    : await getCliRuntime().rolldown_bundle_inventory.attachRolldownBundleHttpPayload(
        source,
        'application/javascript',
      )
  const { stageMetroBundleAssets } = await import('../metro-bundle-assets')
  await stageMetroBundleAssets(file, source, `http://127.0.0.1:${bridgePort}`)
  const url = new URL(
    stageHostBytes(
      prepared === source ? bytes : Buffer.from(prepared, 'utf8'),
      `http://127.0.0.1:${bridgePort}`,
      path.extname(file),
    ),
  )
  url.searchParams.set('dev', String(mode === 'development'))
  return { bundleUrl: url.toString(), port: bridgePort, framework: 'unknown' }
}

function normalizeReplacementPath(filePath: string): string {
  if (filePath.startsWith('~/')) {
    return path.join(os.homedir(), filePath.slice(2))
  }
  if (path.isAbsolute(filePath)) return filePath
  return path.resolve(process.cwd(), filePath)
}

function parseOpenRuntimeConfig(args: string[]): PeachConfig | undefined {
  const modules: NonNullable<PeachConfig['modules']> = {}
  const remap: Record<string, string> = {}

  for (let i = 0; i < args.length; i++) {
    if (args[i] === '--replace') {
      const raw = args[i + 1]
      if (!raw) {
        console.error('  peach open: --replace expects <module>=<file>')
        peachExit(1)
      }
      const eqIndex = raw.indexOf('=')
      if (eqIndex <= 0 || eqIndex === raw.length - 1) {
        console.error('  peach open: --replace expects <module>=<file>')
        peachExit(1)
      }
      const moduleName = raw.slice(0, eqIndex).trim()
      const filePath = normalizeReplacementPath(raw.slice(eqIndex + 1).trim())
      if (!fs.existsSync(filePath)) {
        console.error(`  peach open: replacement file not found: ${filePath}`)
        peachExit(1)
      }
      modules[moduleName] = { file: filePath }
      i++
      continue
    }
    // --remap <host:port>=<host:port> rewrites a guest fetch's host:port at
    // runtime (config.network.remap). repeatable. lets a flow against an app
    // that hardcodes a port reach a differently-bound service.
    if (args[i] === '--remap') {
      const raw = args[i + 1]
      const eqIndex = raw ? raw.indexOf('=') : -1
      if (!raw || eqIndex <= 0 || eqIndex === raw.length - 1) {
        console.error('  peach open: --remap expects <host:port>=<host:port>')
        peachExit(1)
      }
      remap[raw.slice(0, eqIndex).trim()] = raw.slice(eqIndex + 1).trim()
      i++
      continue
    }
  }

  const config: PeachConfig = {}
  if (Object.keys(modules).length > 0) config.modules = modules
  if (Object.keys(remap).length > 0) config.network = { remap }
  return config.modules || config.network ? config : undefined
}

async function ensureConfiguredRuntime(version: string): Promise<void> {
  if (fs.existsSync(path.join(runtimeDir(version), 'index.html'))) return
  console.error(`  installing configured engine runtime ${version}...`)
  const result = await rnxRuntime.install({
    version,
    setActive: false,
    protectVersions: readLiveRuntimeVersions(),
  })
  console.error(`  installed engine runtime ${result.version}`)
}

export function applyRuntimeGenerationOrigin(baseUrl: string, version?: string): string {
  const selectedVersion =
    version ??
    (resolveDevCheckoutRuntimeRoot() ? undefined : (readActiveRuntime() ?? undefined))
  if (!selectedVersion) return baseUrl
  const url = new URL(baseUrl)
  if (!isLoopbackHost(url.hostname)) {
    if (!version) return baseUrl
    throw new Error(
      `runtimeVersion ${selectedVersion} requires a local peach host; got ${url.origin}`,
    )
  }
  url.hostname = runtimeVersionHostname(selectedVersion)
  return url.toString()
}

function deriveCurrentSimBaseUrl(
  sim: BridgeSimInfo | null | undefined,
  fallback: string,
): string {
  const source = sim?.url || sim?.origin || fallback
  try {
    const url = new URL(source)
    url.searchParams.delete('bundle')
    // demo is embed chrome around the next target, like device/theme: the
    // selected-sim rebuild keeps it unless the target overrides it.
    url.searchParams.delete('app')
    url.searchParams.delete('open')
    url.searchParams.delete('port')
    url.searchParams.delete('inspectOpen')
    // appFonts is target-specific (it points at the metro asset endpoint of
    // the bundle being launched). carrying it over from a prior sim URL
    // means a stale font URL from an earlier launch leaks into the new one,
    // and `stampAppFonts` doesn't get the chance to re-derive against the
    // current bundle. drop it so the rebuild starts clean.
    url.searchParams.delete('appFonts')
    url.searchParams.delete('appManifest')
    // appSplash and appCatalog are target-specific in the same way: drop them
    // so the configured splash and catalog re-derive against the current
    // bundle.
    url.searchParams.delete('appSplash')
    url.searchParams.delete('appCatalog')
    url.searchParams.delete('appBundleResources')
    url.searchParams.delete('nativeFirebase')
    url.searchParams.delete('packageVersions')
    url.searchParams.delete('nativeAppIdentity')
    url.searchParams.delete(ANDROID_ROOT_MODULE_QUERY_PARAM)
    url.searchParams.delete(LAUNCH_METADATA_QUERY_PARAM)
    url.searchParams.delete('expoSwift')
    url.searchParams.delete('expoWidgets')
    url.searchParams.delete('expoKotlin')
    url.searchParams.delete('nitro')
    url.searchParams.delete('oneSDK')
    url.searchParams.delete('turbo')
    return url.toString()
  } catch {
    return fallback
  }
}

function withOpenToken(shellUrl: string, openToken: string): string {
  const url = new URL(shellUrl)
  url.searchParams.set('inspectOpen', openToken)
  return url.toString()
}

export async function waitForSimMatch(
  wsPort: number,
  commandTimeoutMs: number,
  predicate: (sim: BridgeSimInfo) => boolean,
  opts: { attempts?: number; intervalMs?: number } = {},
) {
  const attempts = opts.attempts ?? 30
  const intervalMs = opts.intervalMs ?? 500
  for (let i = 0; i < attempts; i++) {
    const bridge = createBridge(wsPort, { commandTimeoutMs })
    try {
      const sims = await bridge.listSims()
      const match = sims.find(predicate)
      if (match) return match
    } catch {
      // server/sim may still be booting
    } finally {
      bridge.close()
    }
    await sleep(intervalMs)
  }
  return null
}

// same as waitForSimMatch, but also watches a detached host PID so a host
// crash mid-connect is surfaced as a distinct outcome rather than waiting
// out the full timeout (and silently treating a stale bridge entry as
// success). 'host-exit' wins as soon as the host process is gone, even if
// the bridge still lists the sim.
export type WaitForSimMatchOrHostExitResult =
  | { kind: 'match'; sim: BridgeSimInfo }
  | { kind: 'host-exit' }
  | { kind: 'timeout' }

export async function waitForSimMatchOrHostExit(
  wsPort: number,
  commandTimeoutMs: number,
  predicate: (sim: BridgeSimInfo) => boolean,
  hostPid: number | undefined,
  opts: {
    attempts?: number
    intervalMs?: number
    signal?: AbortSignal
    admittedFile?: string
  } = {},
): Promise<WaitForSimMatchOrHostExitResult> {
  const attempts = opts.attempts ?? 30
  const intervalMs = opts.intervalMs ?? 500
  const watchHost = !!hostPid && Number.isInteger(hostPid) && hostPid > 1
  const hostExited = () =>
    watchHost && hostPid !== undefined && !isProcessRunning(hostPid)
  // a host queued behind the machine's browser cap has not started its connect
  // budget, so neither does this wait; the caller's signal still bounds it.
  if (opts.admittedFile && watchHost) {
    while (!fs.existsSync(opts.admittedFile)) {
      opts.signal?.throwIfAborted()
      if (hostExited()) return { kind: 'host-exit' }
      await sleep(intervalMs)
    }
  }
  for (let i = 0; i < attempts; i++) {
    opts.signal?.throwIfAborted()
    if (hostExited()) {
      return { kind: 'host-exit' }
    }
    const bridge = createBridge(wsPort, { commandTimeoutMs })
    try {
      const sims = await bridge.listSims()
      const match = sims.find(predicate)
      if (match) {
        if (hostExited()) return { kind: 'host-exit' }
        return { kind: 'match', sim: match }
      }
    } catch {
      // server/sim may still be booting
    } finally {
      bridge.close()
    }
    if (hostExited()) {
      return { kind: 'host-exit' }
    }
    await sleep(intervalMs)
  }
  return { kind: 'timeout' }
}

async function waitForSimGone(
  wsPort: number,
  commandTimeoutMs: number,
  simId: string,
  opts: { attempts?: number; intervalMs?: number } = {},
) {
  const attempts = opts.attempts ?? 20
  const intervalMs = opts.intervalMs ?? 250
  for (let i = 0; i < attempts; i++) {
    const bridge = createBridge(wsPort, { commandTimeoutMs })
    try {
      const sims = await bridge.listSims()
      const sim = sims.find((entry) => entry.id === simId)
      if (!sim || sim.readyState !== 'open') {
        return true
      }
    } catch {
      return true
    } finally {
      bridge.close()
    }
    await sleep(intervalMs)
  }
  return false
}

export function playwrightHostPidForSim(sim: BridgeSimInfo): number | null {
  const meta = sim.meta
  if (!meta || meta.sootsimHostDriver !== 'playwright') return null
  const pid = Number(meta.sootsimHostPid)
  if (!Number.isInteger(pid) || pid <= 1 || pid === process.pid) return null
  return pid
}

export function signalDriverLaunchConnected(result: DriverLaunchResult): boolean {
  if (!result.connectAckFile) return false
  try {
    fs.writeFileSync(
      result.connectAckFile,
      `${JSON.stringify({ connectedAt: Date.now(), pid: result.pid ?? null })}\n`,
      { flag: 'w' },
    )
    return true
  } catch {
    return false
  }
}

// the playwright host exits fast with [unserved] when its initial navigation
// is connection-refused: nothing serves the url, so no sim can ever
// register. surface that as the failure instead of the generic host-crashed
// line below.
function readUnservedUrl(result: DriverLaunchResult): string | null {
  if (!result.diagnosticLogPath) return null
  try {
    const detail = fs.readFileSync(result.diagnosticLogPath, 'utf8')
    const match = detail.match(/\[unserved\] nothing serves (\S+)/)
    return match ? match[1] : null
  } catch {
    return null
  }
}

export function printDriverDiagnosticLogTail(result: DriverLaunchResult) {
  if (!result.diagnosticLogPath) return
  try {
    const detail = fs.readFileSync(result.diagnosticLogPath, 'utf8').trim()
    if (!detail) {
      console.error(`  ${path.basename(result.diagnosticLogPath)} was empty`)
      return
    }
    const shown = detail.length > 4_000 ? `…\n${detail.slice(-4_000)}` : detail
    console.error(`  ${path.basename(result.diagnosticLogPath)}:`)
    console.error(shown)
    if (/No usable sandbox/i.test(detail)) {
      console.error(
        '  this container blocks the user namespaces Chromium sandboxes with. on a locked-down CI runner set PEACH_CHROMIUM_SANDBOX=0 to launch it unsandboxed (the default stays sandboxed).',
      )
    }
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err)
    console.error(
      `  failed to read ${path.basename(result.diagnosticLogPath)}: ${message}`,
    )
  }
}

async function waitForProcessExit(pid: number, timeoutMs = 2_500): Promise<boolean> {
  const deadline = Date.now() + timeoutMs
  while (Date.now() < deadline) {
    if (!isProcessRunning(pid)) return true
    await sleep(25)
  }
  return !isProcessRunning(pid)
}

// a sim record's host pid can outlive its process; after pid reuse the number
// may point at an unrelated process (real incident 2026-07-14: a stale record
// made `peach close` SIGTERM the shared vite shell dev server, taking the
// whole dev stack down). only signal a pid whose argv proves it is still a
// peach playwright host launcher.
function isPlaywrightHostProcess(pid: number): boolean {
  // linux reads the environment from /proc: container images often ship no ps.
  if (process.platform === 'linux') {
    try {
      return fs
        .readFileSync(`/proc/${pid}/environ`, 'utf8')
        .split('\0')
        .some((entry) => entry.startsWith('SOOTSIM_PW_URL='))
    } catch {
      return false
    }
  }
  // `ps eww` prints argv then the process ENVIRONMENT for same-user
  // processes. the marker must live in the env SUFFIX (everything past the
  // plain argv), because argv text can contain the string coincidentally —
  // e.g. a shell wrapper that exports SOOTSIM_PW_* vars in its script body.
  const plain = spawnSync('ps', ['-o', 'command=', '-p', String(pid)], {
    encoding: 'utf8',
    stdio: ['ignore', 'pipe', 'pipe'],
  })
  const withEnv = spawnSync('ps', ['eww', '-o', 'command=', '-p', String(pid)], {
    encoding: 'utf8',
    stdio: ['ignore', 'pipe', 'pipe'],
  })
  if (plain.status !== 0 || withEnv.status !== 0) return false
  const argv = (plain.stdout || '').trimEnd()
  const full = (withEnv.stdout || '').trimEnd()
  const envSuffix = full.startsWith(argv) ? full.slice(argv.length) : full
  return envSuffix.includes('SOOTSIM_PW_URL=')
}

export async function terminatePlaywrightHostsForSims(
  sims: BridgeSimInfo[],
  ids: string[],
) {
  const wanted = new Set(ids)
  const pids = new Set<number>()
  for (const sim of sims) {
    if (!wanted.has(sim.id)) continue
    const pid = playwrightHostPidForSim(sim)
    if (pid) pids.add(pid)
  }
  for (const pid of pids) {
    // a closed sim's host shuts itself down (__sootsimHostClose), so its pid
    // is normally gone by now; only a host still running after that is
    // signalled, and only once its argv proves it is ours.
    if (await waitForProcessExit(pid)) continue
    if (!isPlaywrightHostProcess(pid)) {
      console.log(`  skipped pid ${pid}: not a peach playwright host (stale sim record)`)
      continue
    }
    try {
      process.kill(pid, 'SIGTERM')
    } catch {}
    if (await waitForProcessExit(pid)) {
      console.log(`  closed playwright host process ${pid}`)
      continue
    }
    try {
      process.kill(pid, 'SIGKILL')
      console.log(`  force-closed playwright host process ${pid}`)
    } catch {}
  }
}

function resolveTargetSim(sims: BridgeSimInfo[], requestedId?: string): BridgeSimInfo {
  if (requestedId) {
    const normalizedId = requestedId.trim()
    const match = sims.find((sim) => sim.id === normalizedId)
    if (!match) {
      throw new Error(`no sim connected with id ${normalizedId}`)
    }
    return match
  }
  const primary = sims.find((sim) => sim.isPrimary && sim.readyState === 'open')
  if (primary) return primary
  const firstOpen = sims.find((sim) => sim.readyState === 'open')
  if (firstOpen) return firstOpen
  throw new Error('no sim connected')
}

export function printOpenedSim(
  openUrl: string,
  sim: BridgeSimInfo,
  mode:
    | 'desktop companion'
    | 'bridge'
    | 'direct shell open'
    | 'current sim'
    | `${string} driver`,
  quiet = false,
  json = false,
) {
  const [printableOpenUrl, printableSimUrl] = [openUrl, sim.url].map((value) =>
    value ? redactConfigurationForDiagnostics(value) : value,
  )
  const payload = JSON.stringify({ simId: sim.id, url: printableSimUrl }, null, 2)
  if (quiet) {
    console.log(`  Opened ConnectRN [${mode}]`)
    if (json) process.stdout.write(`${payload}\n`)
    return
  }
  // the launch query carries kilobytes of app identity and fonts; the JSON
  // below keeps the full url, so the human line names only where it opened.
  console.log(
    `  ${mode === 'current sim' ? 'loaded' : 'opened'}: ${urlWithoutQuery(printableOpenUrl)} [${mode}]`,
  )
  // agents pipe around the JSON to grab the id; humans just want to know
  // the current sim got updated without scanning the JSON blob.
  console.log(`  current sim: ${sim.id}`)
  // with --json the status lines above are on stderr, so stdout is the payload
  if (json) process.stdout.write(`${payload}\n`)
  else console.log(payload)
}

function urlWithoutQuery(value: string | undefined): string | undefined {
  if (!value) return value
  try {
    const parsed = new URL(value)
    return `${parsed.origin}${parsed.pathname}`
  } catch {
    return value
  }
}

function printAgentHints(quiet: boolean): void {
  if (quiet) return
  console.log('  inspect messages: run `peach agent listen` when you finish your turn')
  if (!hasInstalledPeachSkills()) {
    console.log('  driving peach from an agent? `peach skill install` adds its workflows')
  }
}

// after a successful open, agents almost always want to know what's on the
// screen. running describe inline saves a separate roundtrip. tightly
// bounded — a cold guest bundle takes 5-15s to fully route, so we don't
// try to wait for that. instead: settle for a moment to let the first
// paint land, then describe whatever's on screen. for cold loads that's
// a splash; the caller can `peach describe` again a second later. for
// warm loads it's the real screen. guarded by --no-describe.
async function maybeDescribeAfterOpen(wsPort: number, simId: string, args: string[]) {
  const noDescribe = args.includes('--no-describe')
  if (noDescribe && !diagnosticsAllowedForCurrentProcess()) return
  const prevQuiet = process.env.PEACH_QUIET_TARGET_NOTICE
  process.env.PEACH_QUIET_TARGET_NOTICE = '1'
  try {
    // brief settle, then dump the tree directly. don't go through
    // runDescribeSubcommand — its screen-transition wait can block for many
    // seconds on a still-routing guest app, which is exactly what we want
    // to skip for the open-side describe. caller can `peach describe`
    // again later for post-routing state.
    if (!noDescribe) await waitForTreeStable(wsPort, simId, { stableMs: 150, maxMs: 400 })
    const bridge = createBridge(wsPort, {
      commandTimeoutMs: 3000,
      simId,
      cliLabel: 'open --describe',
      simIdSource: 'flag',
    })
    try {
      if (noDescribe) return
      // the tree just held still, so one probe says whether the app is up
      let readyProbe: Awaited<ReturnType<typeof inspectReadySnapshot>> | null = null
      try {
        readyProbe = await inspectReadySnapshot(bridge, 3000)
      } catch {}
      if (readyProbe && !readyProbe.ready) {
        console.log(
          `  app still loading: ${waitReadyReason(readyProbe)} (nodes: ${readyProbe.nodes}, targets: ${readyProbe.targets})`,
        )
        console.log('  before interacting, run: peach wait ready')
      }
      const result = await inspectDescribe(bridge, {
        describe: true,
        verbose: false,
        filter: '',
        compact: true,
        hideXy: false,
      })
      if (!result?.tree) return
      console.log('')
      console.log(result.tree)
    } finally {
      await collectRuntimeDiagnostics(bridge)
      bridge.close()
    }
  } catch {
    // describe is a convenience — never fail the open command on it
  } finally {
    if (prevQuiet === undefined) {
      delete process.env.PEACH_QUIET_TARGET_NOTICE
    } else {
      process.env.PEACH_QUIET_TARGET_NOTICE = prevQuiet
    }
  }
}

// poll node count and return as soon as two samples match across `stableMs`,
// capped by `maxMs`. brief and bounded so this never blocks the open command.
async function waitForTreeStable(
  wsPort: number,
  simId: string,
  opts: { stableMs: number; maxMs: number },
): Promise<void> {
  const deadline = Date.now() + opts.maxMs
  const probeCode = `(async () => (await globalThis.__sootsimTest?.getNodeCount?.()) || 0)()`
  const bridge = createBridge(wsPort, {
    commandTimeoutMs: 2000,
    simId,
    simIdSource: 'flag',
  })
  try {
    let lastCount = -1
    let stableSince = 0
    while (Date.now() < deadline) {
      let count = -1
      try {
        const c = await bridge.send({ type: 'evaluate', code: probeCode })
        if (typeof c === 'number') count = c
      } catch {
        // transient — try again
      }
      if (count >= 0 && count === lastCount) {
        if (Date.now() - stableSince >= opts.stableMs) return
      } else {
        lastCount = count
        stableSince = Date.now()
      }
      await sleep(50)
    }
  } finally {
    bridge.close()
  }
}

export async function runLinkCommand(args: string[], opts: ControlCommandOptions = {}) {
  const parsed = parseBridgeCliArgs(args, {
    port: opts.port,
    commandTimeoutMs: opts.timeoutMs,
  })
  await dispatchAppLink(parsed)
}

// device/theme seed the selected live sim through the settings bridge, the
// same call `peach device set` makes, before the link is delivered
async function dispatchAppLink(
  parsed: ParsedBridgeCliArgs,
  liveSettings: { device?: string; theme?: string } = {},
) {
  if (parsed.positional.length !== 1) {
    console.error('  peach open: expected exactly one <url-or-route>')
    console.error('  examples: peach open /settings  |  peach open myapp://settings')
    peachExit(1)
  }

  const bridge = createBridgeFromParsed(parsed)
  const simHint = parsed.simId ? ` --sim ${parsed.simId}` : ''
  try {
    for (const [key, value] of [
      ['deviceModel', liveSettings.device],
      ['colorScheme', liveSettings.theme],
    ] as const) {
      if (value)
        await callInBridgeWrite(bridge, 'SootSim.bridges.settings.set', key, value)
    }
    const target = await openAppUrl(bridge, parsed.positional[0] ?? '')
    console.log(`  opened deep link: ${target}`)
  } catch (err) {
    console.error(`  link failed: ${err instanceof Error ? err.message : String(err)}`)
    await printBridgeFailureDiagnostics(bridge, {
      errorsCommand: `peach get errors 5${simHint}`,
      warningsCommand: `peach get warnings 5${simHint}`,
      requestsCommand: `peach get requests 5${simHint}`,
    })
    peachExit(1)
  } finally {
    bridge.close()
  }
}

type OpenCommandOptions = ControlCommandOptions & {
  // permissions the app this open boots holds from its first read, as a
  // test runner sets them before it launches the app
  launchPermissions?: SystemPermissionBootSeed['presets']
  resources?: OpenCommandResources
  signal?: AbortSignal
  ownerPid?: number
}

// `--json` makes stdout exactly the {simId, url} payload: every other line
// the open path prints (progress, describe tree, hints) goes to stderr.
export async function runOpenCommand(
  args: string[],
  opts: OpenCommandOptions = {},
): Promise<{ simId: string; launched: boolean } | undefined> {
  const { STREAM_FLAG, runStreamCommand } = await import('./stream')
  if (args.includes(STREAM_FLAG)) {
    const { authHeaderOrExit } = await import('../auth')
    authHeaderOrExit('stream')
    const opened = await runOpenCommand(
      args.filter((arg) => arg !== STREAM_FLAG),
      opts,
    )
    if (opened)
      await runStreamCommand(['start', '--sim', opened.simId], { port: opts.port })
    return opened
  }
  if (!args.includes('--json')) return openSim(args, opts)
  const log = console.log
  console.log = console.error
  try {
    return await openSim(args, opts)
  } finally {
    console.log = log
  }
}

async function openSim(
  args: string[],
  opts: OpenCommandOptions,
): Promise<{ simId: string; launched: boolean } | undefined> {
  // an ipa or apk we built opens as the plain bundle it carries
  const binary = args.find((arg) => !arg.startsWith('-') && isAppBinaryPath(arg))
  if (binary) {
    try {
      const { bundlePath, platform } = extractAppBinaryBundle(binary)
      args = args.map((arg) => (arg === binary ? bundlePath : arg))
      if (platform === 'android' && !args.includes('--device') && !args.includes('-d'))
        args = [...args, '--device', 'pixel-8']
    } catch (error) {
      console.error(
        `  peach open: ${error instanceof Error ? error.message : String(error)}`,
      )
      peachExit(1)
    }
  }
  const openArgOptions = {
    stripBooleanFlags: [
      '--new',
      '--headless',
      '--chromium',
      '--headed',
      '--ephemeral',
      '--hot',
      '--no-hmr',
      '--no-describe',
      '--quiet',
      '--json',
      '--proof',
      '--load-env',
      '--upload-source',
      '--no-open',
    ],
    stripValueFlags: [
      '--base-url',
      '--bundle-origin',
      '--project-root',
      '--app-fonts-dir',
      '--native-renderer',
      '--replace',
      '--remap',
      '--driver',
      '--profile',
      '--id',
      '--cdp-port',
      '--device',
      '-d',
      '--posture',
      '--render-resolution',
      '--predictive-text',
      '--orientation',
      '--window',
      '--os-version',
      '--ios-target',
      '--target',
      '--scheme',
      '--activity',
      '--variant',
      '--host-port',
      '--swift-sdks-path',
      '--viewport',
      '--env',
      '--arg',
      '--theme',
      '-t',
    ],
  }
  const booleanFlags = new Set(openArgOptions.stripBooleanFlags)
  const valueFlags = new Set(openArgOptions.stripValueFlags)
  const bridgeValueFlags = new Set(BRIDGE_VALUE_FLAGS)
  // validate tokens, not parsed positionals: option values may start with a
  // dash, and an explicit separator ends option validation.
  for (let i = 0; i < args.length; i++) {
    const arg = args[i]
    if (arg === '--') break
    if (valueFlags.has(arg) || bridgeValueFlags.has(arg)) {
      i++
      continue
    }
    if (booleanFlags.has(arg)) continue
    const equals = arg.indexOf('=')
    if (equals > 0 && bridgeValueFlags.has(arg.slice(0, equals))) continue
    const globalTakesValue = GLOBAL_FLAG_TAKES_VALUE.get(arg)
    if (globalTakesValue !== undefined) {
      if (globalTakesValue) i++
      continue
    }
    if (arg.startsWith('-') && arg !== '-') {
      console.error(
        `  peach open: unknown option "${arg}". ${
          arg.startsWith('--cdp') ? 'Use --cdp-port <port>. ' : ''
        }Run \`peach open --help\` for supported options.`,
      )
      peachExit(1)
    }
  }
  const parsed = parseBridgeCliArgs(args, {
    ...openArgOptions,
    port: opts.port,
    commandTimeoutMs: opts.timeoutMs,
  })
  const requestedProfileId = args.find((_, i) => args[i - 1] === '--profile')
  const agentIdFlag = args.indexOf('--id')
  if (agentIdFlag !== -1) {
    const agentId = args[agentIdFlag + 1]?.trim()
    if (!agentId || agentId.startsWith('-')) {
      console.error('  peach open: --id expects a name, such as --id checkout-agent')
      peachExit(1)
    }
    saveAgentId(agentId)
  }
  const quiet = args.includes('--quiet')
  const json = args.includes('--json')
  const ephemeralProfile = args.includes('--ephemeral')
  // --cdp-port exposes Chrome's remote-debugging endpoint on the opened sim so
  // it can be cpu-profiled while bridge-driven (playwright driver only).
  const cdpPortArg = args.find((_, i) => args[i - 1] === '--cdp-port')
  const cdpPort = cdpPortArg ? Number(cdpPortArg) : undefined
  if (cdpPortArg && (!Number.isFinite(cdpPort) || cdpPort! <= 0)) {
    console.error(
      `  peach open: --cdp-port must be a positive port number, got "${cdpPortArg}"`,
    )
    peachExit(1)
  }
  if (requestedProfileId && ephemeralProfile) {
    console.error('  peach open: --profile cannot be combined with --ephemeral')
    peachExit(1)
  }
  const profileId = requestedProfileId ? ensureProfile(requestedProfileId).id : undefined
  const openInNewSim = args.includes('--new') || !!profileId || ephemeralProfile
  const commandConfig = parseOpenRuntimeConfig(args)
  if (openInNewSim && parsed.simIdSource === 'flag') {
    console.error(
      '  peach open: --new, --profile, and --ephemeral cannot be combined with --sim',
    )
    peachExit(1)
  }
  const target = parsed.positional[0] || ''

  // `--port` is the WS BRIDGE port; the app/dev-server port is positional. the
  // two read identically at a glance, so `peach open --new --port 4260` used to
  // launch the Connect launcher against the default bridge and report success,
  // and the probe that followed measured whatever sim happened to be selected.
  // without a target, `open --port` only means a live bridge to open on; a
  // port that does not answer the bridge protocol is refused.
  if (!target && args.includes('--port') && !(await isLiveBridge(parsed.wsPort))) {
    const portValue = args[args.indexOf('--port') + 1] ?? '<number>'
    console.error(
      `  peach open: nothing on port ${portValue} answers the bridge protocol. --port is the WS bridge port, not the app port. to open the app on ${portValue}, pass it positionally: \`peach open ${portValue}\``,
    )
    peachExit(1)
  }

  // -t / --theme <light|dark|auto> seeds the appearance for the opened sim,
  // stamped on the engine URL as ?theme= next to ?device=: the shell reads it
  // at boot over the persisted scheme. without this the flag fell into the
  // positional target (`peach open -t dark` opened `?open=-t`) and the theme
  // was silently dropped. validated up here so a bad flag fails before the
  // bridge spawns.
  const themeFlagIndex = args.findIndex((arg) => arg === '--theme' || arg === '-t')
  const themeArg = themeFlagIndex === -1 ? undefined : args[themeFlagIndex + 1]
  if (themeFlagIndex !== -1 && themeArg === undefined) {
    console.error('  peach open: --theme expects light, dark, or auto')
    peachExit(1)
  }
  if (
    themeArg !== undefined &&
    themeArg !== 'light' &&
    themeArg !== 'dark' &&
    themeArg !== 'auto'
  ) {
    console.error(`  peach open: --theme must be light, dark, or auto, got "${themeArg}"`)
    peachExit(1)
  }

  const { resolveNativeInput } = await import('../native-input')
  const nativeInput = resolveNativeInput(target)
  if (nativeInput) {
    const nativeArgs = [nativeInput.path]
    const openArgs: string[] = []
    // the native host reads these; everything else configures the preview
    const nativeValueFlags = new Set([
      '--target',
      '--scheme',
      '--activity',
      '--variant',
      '--host-port',
      '--swift-sdks-path',
    ])
    const nativeBooleanFlags = new Set(['--upload-source', '--no-open'])
    for (let index = 0; index < args.length; index++) {
      const arg = args[index]
      if (index === args.indexOf(target)) continue
      if (nativeValueFlags.has(arg)) nativeArgs.push(arg, args[++index])
      else if (nativeBooleanFlags.has(arg)) nativeArgs.push(arg)
      else openArgs.push(arg)
    }
    const code =
      nativeInput.kind === 'kotlin'
        ? await (
            await import('./kotlin')
          ).runKotlin(nativeArgs, { port: opts.port, openArgs })
        : await (
            await import('./swift')
          ).runSwift(nativeArgs, { port: opts.port, openArgs })
    if (code) peachExit(code)
    return
  }

  // an absolute path to a built bundle is a file, not an app path
  const prebuiltBundle = prebuiltBundleFile(target)
  if (!prebuiltBundle && isAppDeepLinkTarget(target)) {
    if (openInNewSim) {
      console.error(
        '  peach open: deep links target the current app; remove --new, --profile, or --ephemeral',
      )
      peachExit(1)
    }
    const linkDevice = args.find((_, i) => args[i - 1] === '--device')
    if (!validateDeviceOption(linkDevice)) peachExit(1)
    await dispatchAppLink(parsed, { device: linkDevice, theme: themeArg })
    return
  }

  // a preview/build link is a viewing page, not a driveable sim target —
  // open it in the browser and explain rather than mis-loading it as a
  // bundle. see looksLikeSootSimShareUrl for why these can't be driven.
  if (looksLikeSootSimShareUrl(target)) {
    const isLocal = (() => {
      try {
        return isLoopbackHost(new URL(target).hostname)
      } catch {
        return false
      }
    })()
    console.log(
      '  that’s a peach preview/build link — a full player page, not a driveable sim.',
    )
    if (!isTeamMachineSession()) console.log('  opening it in your browser for viewing…')
    try {
      await openUrlInBrowser(target, { background: false })
    } catch (err) {
      console.error(
        `  could not launch a browser: ${err instanceof Error ? err.message : String(err)}`,
      )
      console.error(`  open it yourself: ${target}`)
      peachExit(1)
    }
    console.log(
      isLocal
        ? '  to drive it under the CLI, point `peach open` at the app’s dev port instead (e.g. `peach open 8081`).'
        : '  the CLI can’t drive a remote preview (the engine only attaches to the local bridge from localhost). to drive the app, run it locally and `peach open <port>`.',
    )
    return
  }

  // argument validation and link handling are done; every failure from here on
  // happens while choosing the sim this open meant to drive. an open that will
  // not reuse a pinned sim records that intent now, so a failure anywhere
  // below leaves later implicit commands refused instead of landing on
  // whichever other tab the bridge holds.
  const savedSimId = readCurrentSimId()
  if (parsed.simIdSource !== 'flag' && (openInNewSim || !savedSimId)) markOpenPending()

  // a bundle file gets its url once the bridge that serves it is settled
  let resolvedBundle =
    !prebuiltBundle && shouldResolveBundleTargetInCli(target)
      ? await resolveConnectionInputForCli(target, opts.signal)
      : undefined
  const projectRootIndex = args.indexOf('--project-root')
  const projectRoot = projectRootIndex < 0 ? undefined : args[projectRootIndex + 1]
  if (projectRootIndex >= 0 && (!projectRoot || projectRoot.startsWith('--'))) {
    console.error('  peach open: --project-root expects a local app directory')
    peachExit(1)
  }
  const project = await resolveAppProjectForBundleUrl(
    resolvedBundle?.bundleUrl,
    projectRoot,
    resolvedBundle?.manifestProjectRoot,
    opts.signal,
  )
  startExpoConfigRead(project)
  // playwright is the browser-sim launcher. it owns an isolated profile and
  // can reap exactly its own browser tree. desktop opens the native host and
  // electron the Electron companion. none opens the user's browser profile.
  const requestedDriverId = args.find((_, i) => args[i - 1] === '--driver') || ''
  if (requestedDriverId && !isDriverId(requestedDriverId)) {
    console.error(
      `  unknown driver "${requestedDriverId}" — run \`peach list --drivers\``,
    )
    peachExit(1)
  }
  // a person watching the sim, directly or through their coding agent, gets the
  // native app where it ships. CI and Team Machine fleet sessions stay in the
  // headless browser, as do the browser-only --headless and --chromium.
  const defaultDriverId: DriverId =
    isCi() ||
    isTeamMachineSession() ||
    args.includes('--headless') ||
    args.includes('--chromium')
      ? 'playwright'
      : (readSimulatorDriverPreference() ??
        (nativeDesktopIsDefault() ? 'desktop' : 'playwright'))
  const selectedDriverId = isDriverId(requestedDriverId)
    ? requestedDriverId
    : defaultDriverId
  const driverId: DriverId =
    selectedDriverId === 'electron' && process.platform !== 'win32'
      ? 'desktop'
      : selectedDriverId
  if (requestedDriverId === 'electron' && driverId === 'desktop')
    console.error(
      '  Electron is Windows-only; using the native desktop app (peach desktop install).',
    )
  // the first open on a machine without the native app installs it.
  if (driverId === 'desktop' && !findDesktopCompanion())
    await runInstallDesktop(['--yes'])
  const driverHeadless = resolveDriverHeadless(args, driverId)
  const chromium = args.includes('--chromium')
  if (chromium && driverId !== 'playwright') {
    console.error('  peach open: --chromium requires the playwright driver')
    peachExit(1)
  }
  const renderer = chromium
    ? 'chromium'
    : driverHeadless && desktopHostPlatform() === 'linux-x64'
      ? 'native'
      : undefined
  const pinnedHostExecutable =
    !chromium &&
    driverHeadless &&
    desktopHostPlatform() === 'linux-x64' &&
    desktopHostDelivery().resolvePin()
      ? (headlessHostCommand()?.[0] ?? null)
      : undefined
  if (cdpPort && driverId !== 'playwright') {
    console.error('  peach open: --cdp-port is only honored by the playwright driver')
    peachExit(1)
  }

  // metro HMR mode. interactive opens default to hot=true so edits hot-apply
  // through peach's HmrClient — expo CLI's createBundleUrlSearchParams
  // hardcodes hot=false on every launchAsset URL (a leftover toggle real iOS
  // sims tolerate but peach couldn't until now), so without this flip the
  // bundle prelude doesn't include metro's HMR runtime + react-refresh and
  // edits silently no-op. `--driver playwright` (agent / CI runs) defaults
  // to hot=false for deterministic e2e. explicit `--hot` / `--no-hmr` win.
  const hotFlag = args.includes('--hot')
  const noHmrFlag = args.includes('--no-hmr')
  if (hotFlag && noHmrFlag) {
    console.error('  peach open: --hot and --no-hmr cannot be combined')
    peachExit(1)
  }
  const hotMode = hotFlag ? true : noHmrFlag ? false : driverId !== 'playwright'

  // --device <model> seeds the device profile for the opened sim (stamped on
  // the engine URL, so both playwright and electron honor it). without it
  // the sim runs whatever profile the
  // shell last persisted, which silently skews browser comparisons.
  const deviceArg = args.find(
    (_, i) => args[i - 1] === '--device' || args[i - 1] === '-d',
  )
  if (!validateDeviceOption(deviceArg)) peachExit(1)

  // asked before the bundle so the dev server answers it ahead of the build
  const oneAppSplash =
    resolvedBundle && project && !findExpoAppConfig(project.appDir)
      ? discoverOneNativeAppSplash(resolvedBundle.bundleUrl)
      : undefined
  const explicitBaseUrl = args.find((_, i) => args[i - 1] === '--base-url')
  const baseUrlConfig = explicitBaseUrl
    ? readPeachConfigFromSearchParams(new URL(explicitBaseUrl).searchParams)
    : undefined
  const appConfig = await loadRNXAppConfig(project)
  const configuredRuntimeVersion = appConfig?.runtimeVersion
  const runtimeConfig = mergePeachConfig(
    mergePeachConfig(
      mergePeachConfig(
        appConfig ? { ...appConfig, runtimeVersion: undefined } : undefined,
        baseUrlConfig,
      ),
      opts.runtimeConfig,
    ),
    commandConfig,
  )
  if (configuredRuntimeVersion) {
    await ensureConfiguredRuntime(configuredRuntimeVersion)
  }

  // keep the bridge port and the shell base URL in one world: --base-url
  // retargets polling at THAT world's bridge (otherwise open builds the page
  // against one runtime while polling the other bridge for registration and
  // times out after ~125s), and a pin nothing serves is refused rather than
  // falling back to the discovered default, which used to send
  // ensureBridgeForOpen below off to start a second shell.
  if (explicitBaseUrl) {
    const pinned = resolveBridgePortForPin({
      baseUrl: explicitBaseUrl,
      wsPort: parsed.wsPort,
      explicitPort: parsed.explicitPort,
    })
    if (pinned.error !== undefined) {
      console.error(`  error: ${pinned.error}`)
      peachExit(1)
    } else {
      parsed.wsPort = pinned.port
    }
  }

  opts.signal?.throwIfAborted()
  parsed.wsPort = await ensureBridgeForOpen(
    parsed.wsPort,
    parsed.explicitPort,
    opts.resources,
    !configuredRuntimeVersion &&
      (explicitBaseUrl ||
        looksLikeSootsimUrl(target) ||
        (parsed.explicitPort &&
          worldForBridgePort(parsed.wsPort)?.source === 'dev-bridge'))
      ? 'external'
      : 'bridge',
    {
      newShell: openInNewSim,
      simId: parsed.simId,
      simIdSource: parsed.simIdSource,
      driverId,
      renderer,
      pinnedHostExecutable,
    },
  )
  if (opts.resources) opts.resources.port = parsed.wsPort
  opts.signal?.throwIfAborted()
  if (resolvedBundle) {
    // platform selection needs the verified companion after runtime preparation
    const bundleUrl = applyHotMode(resolvedBundle.bundleUrl, hotMode)
    // a reused sim keeps its own device, so the engine asks for that device's
    // platform even when this open names none
    const reusedSimId =
      parsed.simIdSource === 'flag'
        ? parsed.simId
        : parsed.simIdSource === 'saved' && !openInNewSim
          ? savedSimId
          : undefined
    const warmDevice =
      deviceArg ??
      (reusedSimId
        ? await readSimDevice(createBridgeFromParsed(parsed), reusedSimId)
        : null)
    startDevServerBuild(
      warmDevice && isDeviceModel(warmDevice)
        ? getCliRuntime().bundle_platform_url.bundleUrlForPlatform(
            bundleUrl,
            getCliRuntime().settings_devices.getRuntimePlatform(warmDevice),
            () => bundleUrl,
          )
        : bundleUrl,
    )
  }
  // the shell opens a bundle file as the url the bridge serves it at
  let shellTarget = target
  if (prebuiltBundle) {
    try {
      resolvedBundle = await stagePrebuiltBundle(prebuiltBundle, parsed.wsPort)
      shellTarget = resolvedBundle.bundleUrl
    } catch (error) {
      console.error(
        `  peach open: ${error instanceof Error ? error.message : String(error)}`,
      )
      peachExit(1)
    }
  }

  // --posture <closed|book|open|laptop|tent> seeds the fold rest for the
  // opened sim, stamped on the engine URL next to ?device= so it round-trips
  // instead of being swallowed into the bundle param. only foldable devices
  // (iphone-duo) fold; anything else resolves to closed at boot. the display
  // posture and interface orientation the rest lays out ride beside it.
  const postureArg = args.find((_, i) => args[i - 1] === '--posture')
  const foldBus = getCliRuntime().settings_duo_fold_bus
  const postureRest = postureArg ?? null
  const restArg = foldBus.isDuoFoldRest(postureRest) ? postureRest : undefined
  if (postureArg && !restArg) {
    console.error(
      `  peach open: --posture must be ${Object.keys(foldBus.DUO_REST_PROGRESS).join(', ')}, got "${postureArg}"`,
    )
    peachExit(1)
  }
  const renderResolutionArg = args.find((_, i) => args[i - 1] === '--render-resolution')
  if (
    args.includes('--render-resolution') &&
    renderResolutionArg !== 'high' &&
    renderResolutionArg !== 'medium' &&
    renderResolutionArg !== 'low'
  ) {
    console.error(
      `  peach open: --render-resolution must be high, medium, or low, got "${renderResolutionArg ?? ''}"`,
    )
    peachExit(1)
  }
  const predictiveTextArg = args.find((_, i) => args[i - 1] === '--predictive-text')
  if (
    args.includes('--predictive-text') &&
    predictiveTextArg !== 'on' &&
    predictiveTextArg !== 'off'
  ) {
    console.error(
      `  peach open: --predictive-text must be on or off, got "${predictiveTextArg ?? ''}"`,
    )
    peachExit(1)
  }
  const orientationFlag = args.find((_, i) => args[i - 1] === '--orientation')
  const orientationArg =
    orientationFlag === 'portrait' || orientationFlag === 'landscape'
      ? orientationFlag
      : undefined
  if (orientationFlag && !orientationArg) {
    console.error(
      `  peach open: --orientation must be portrait or landscape, got "${orientationFlag}"`,
    )
    peachExit(1)
  }
  // --window <WxH> opens the dynamic device's window at that size in points;
  // the shell clamps it to the iPadOS window limits
  const windowArg = args.find((_, i) => args[i - 1] === '--window')
  const windowMatch = windowArg ? /^(\d+)x(\d+)$/.exec(windowArg) : null
  if (windowArg && (!windowMatch || deviceArg !== 'dynamic')) {
    console.error(
      `  peach open: --window takes <width>x<height> with --device dynamic, got "${windowArg}"`,
    )
    peachExit(1)
  }
  const windowSize = windowMatch
    ? { width: Number(windowMatch[1]), height: Number(windowMatch[2]) }
    : undefined
  // the window fits the box the browser stage fits the device into, which for
  // a foldable spans both postures, so the device draws at its natural size in
  // the posture it opens in instead of shrinking into a window sized for one.
  const deviceFitBox =
    windowSize ??
    (deviceArg
      ? getCliRuntime().settings_devices.resolveDeviceFitBox(
          deviceArg as DeviceModel,
          false,
          orientationArg,
          restArg ? foldBus.duoRestPosture(restArg) : 'closed',
        )
      : undefined)

  // --os-version <major.minor> pins the portrayed os over the profile's.
  const osVersionArg = args.find((_, i) => args[i - 1] === '--os-version')
  if (osVersionArg && !/^\d+\.\d+$/.test(osVersionArg)) {
    console.error(
      `  peach open: --os-version must be <major>.<minor>, got "${osVersionArg}"`,
    )
    peachExit(1)
  }

  // --env <KEY=VALUE> (repeatable) sets a launch-time environment variable,
  // the peach analogue of an Xcode scheme env var or SIMCTL_CHILD_<VAR>:
  // stamped as repeated ?env=, carried on AppLoadRequest, and read into a
  // Swift guest's ProcessInfo.environment (WASI environ) exactly as it would
  // read a real launch env. the guest app opts in by reading the key itself;
  // no other surface is affected.
  const envArgs: string[] = []
  for (let i = 0; i < args.length; i++) {
    if (args[i] !== '--env') continue
    const raw = args[i + 1]
    const eqIndex = raw ? raw.indexOf('=') : -1
    if (!raw || eqIndex <= 0) {
      console.error(`  peach open: --env expects KEY=VALUE, got "${raw ?? ''}"`)
      peachExit(1)
    }
    envArgs.push(raw)
  }

  // --arg <value> (repeatable) is one launch argument, the peach analogue of
  // a `simctl launch` argument: stamped as repeated ?arg=, carried on
  // AppLoadRequest, and handed to a Swift guest as ProcessInfo.arguments[1...]
  // verbatim, each value its own element after the executable path.
  const launchArgs = args.flatMap((arg, i) => (args[i - 1] === '--arg' ? [arg] : []))
  if (args.at(-1) === '--arg') {
    console.error('  peach open: --arg expects a value')
    peachExit(1)
  }

  // --viewport <WxH> sizes the driver-launched page explicitly (film and
  // promo captures frame the 3d stage in landscape). takes precedence over
  // the device-derived window; without either, the driver keeps its own
  // default.
  const viewportArg = args.find((_, i) => args[i - 1] === '--viewport')
  const viewportMatch = viewportArg ? /^(\d+)x(\d+)$/.exec(viewportArg) : null
  if (viewportArg && !viewportMatch) {
    console.error(
      `  peach open: --viewport must be <width>x<height>, got "${viewportArg}"`,
    )
    peachExit(1)
  }
  const explicitViewport = viewportMatch
    ? { width: Number(viewportMatch[1]), height: Number(viewportMatch[2]) }
    : undefined

  // --load-env reads the project's env file the way react-native-config's iOS
  // build phase compiles it into the binary (ENVFILE, then .env), so the app's
  // `Config` holds those values. without it `Config` is empty, as in a build
  // that found no env file, and the app's first read warns in the console.
  let dotEnv: Record<string, string> | undefined
  if (args.includes('--load-env')) {
    if (!project) {
      console.error(
        '  peach open: --load-env needs a local app project to read the env file from',
      )
      peachExit(1)
    }
    try {
      const result = readProjectDotEnv(project.appDir)
      if (!quiet) for (const notice of result.notices) console.log(`  ${notice}`)
      dotEnv = result.config
    } catch (error) {
      console.error(
        `  peach open: ${error instanceof Error ? error.message : String(error)}`,
      )
      peachExit(1)
    }
  }

  const buildShellUrlOpts: BuildShellUrlOptions = {
    bundleOriginOverride: args.find((_, i) => args[i - 1] === '--bundle-origin'),
    appFontsDir: args.find((_, i) => args[i - 1] === '--app-fonts-dir'),
    nativeRenderer: readNativeRenderer(
      args.find((_, i) => args[i - 1] === '--native-renderer'),
    ),
    hot: hotMode,
    hostDriver: driverId === 'desktop' ? 'desktop' : undefined,
    device: deviceArg,
    posture: restArg ? foldBus.duoRestPosture(restArg) : undefined,
    rest: restArg,
    renderResolution: renderResolutionArg,
    predictiveText:
      predictiveTextArg === undefined ? undefined : predictiveTextArg === 'on',
    orientation:
      orientationArg ??
      (restArg
        ? foldBus.duoRestOrientation(restArg, foldBus.duoRestTurnsBody(restArg))
        : undefined),
    windowSize,
    osVersion: osVersionArg,
    theme: themeArg,
    // --target selects the Xcode application target on native opens; honor it
    // on dev-server opens too, where the multi-target error sends strangers
    iosTarget:
      args.find((_, i) => args[i - 1] === '--ios-target') ??
      args.find((_, i) => args[i - 1] === '--target'),
    resolvedBundle,
    project,
    oneAppSplash,
    proof: args.includes('--proof'),
    ephemeral: ephemeralProfile,
    env: envArgs.length ? envArgs : undefined,
    args: launchArgs.length ? launchArgs : undefined,
    dotEnv,
    bridgePort: parsed.explicitPort ? parsed.wsPort : undefined,
  }

  // resolve the shell base URL from the bridge port we settled on, so the page
  // and the polling never split across worlds.
  const selectedShellBaseUrl = configuredRuntimeVersion
    ? `http://localhost:${parsed.wsPort}/`
    : explicitBaseUrl || resolveShellBaseUrlForBridgePort(parsed.wsPort)
  const baseUrl =
    explicitBaseUrl && !configuredRuntimeVersion
      ? selectedShellBaseUrl
      : applyRuntimeGenerationOrigin(selectedShellBaseUrl, configuredRuntimeVersion)
  const hasExplicitBaseUrl = args.includes('--base-url')
  printBridgeWorldNotice(parsed.wsPort, baseUrl)
  const shouldReuseCurrentSim = !openInNewSim
  // every open stamps its page URL with a one-off token and matches the sim by
  // it. a sim id alone cannot tell the page this open loaded from the page it
  // replaced, which stays registered until the browser commits the navigation.
  const token = `cli-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
  const simMatchesToken = (sim: BridgeSimInfo) =>
    sim.url?.includes(`inspectOpen=${token}`) ?? false

  // the reuse check builds the page url a new sim loads; building it once
  // keeps the project's native config read, a node spawn, to one per open
  let newSimShellUrl: string | null = null
  if (shouldReuseCurrentSim) {
    const bridge = createBridgeFromParsed(parsed)
    const simHint = parsed.simId ? ` --sim ${parsed.simId}` : ''
    let fallBackToNewSim = false
    let navigatedShellUrl: string | null = null

    try {
      let targetSim: BridgeSimInfo | null = null
      let targetShellUrl: string | null = null
      try {
        const sims = await bridge.listSims()
        if (parsed.simIdSource === 'saved') {
          targetSim =
            sims.find(
              (sim) =>
                sim.id === savedSimId &&
                sim.readyState === 'open' &&
                simUsesDriver(sim, driverId, renderer, pinnedHostExecutable),
            ) ?? null
          if (!targetSim) {
            markOpenPending()
          }
        } else if (parsed.simIdSource === 'flag') {
          targetSim = resolveTargetSim(sims, parsed.simId)
          if (!simUsesDriver(targetSim, driverId, renderer, pinnedHostExecutable)) {
            throw new Error(
              `sim ${targetSim.id} is not managed by the ${driverId} driver`,
            )
          }
        }
        if (!targetSim && parsed.simIdSource !== 'flag') {
          targetShellUrl = newSimShellUrl = await buildShellUrl(
            shellTarget,
            applyPeachConfigToUrl(baseUrl, runtimeConfig),
            buildShellUrlOpts,
          )
          const normalizedTarget = new URL(targetShellUrl)
          normalizedTarget.searchParams.delete('inspectOpen')
          targetSim =
            sims.find((sim) => {
              if (
                sim.readyState !== 'open' ||
                !sim.url ||
                !simUsesDriver(sim, driverId, renderer, pinnedHostExecutable)
              ) {
                return false
              }
              try {
                const normalizedCurrent = new URL(sim.url)
                normalizedCurrent.searchParams.delete('inspectOpen')
                return normalizedCurrent.toString() === normalizedTarget.toString()
              } catch {
                return false
              }
            }) ?? null
        }
        if (!targetSim) {
          if (parsed.simIdSource !== 'flag') {
            fallBackToNewSim = true
          } else {
            throw new Error('no sim connected')
          }
        }
        if (!fallBackToNewSim && targetSim) {
          const resolvedBaseUrl =
            hasExplicitBaseUrl || looksLikeSootsimUrl(target)
              ? baseUrl
              : deriveCurrentSimBaseUrl(targetSim, baseUrl)
          navigatedShellUrl =
            targetShellUrl ??
            (await buildShellUrl(
              shellTarget,
              applyPeachConfigToUrl(resolvedBaseUrl, runtimeConfig),
              buildShellUrlOpts,
            ))
          const navigationUrl = new URL(navigatedShellUrl)
          const currentEphemeral = new URL(
            deriveCurrentSimBaseUrl(targetSim, baseUrl),
          ).searchParams.get('ephemeral')
          if (currentEphemeral)
            navigationUrl.searchParams.set('ephemeral', currentEphemeral)
          navigatedShellUrl = navigationUrl.toString()
          navigationUrl.searchParams.set('inspectOpen', token)
          await awaitStampedExpoSwiftReady(
            navigatedShellUrl,
            token,
            shellUrlPlatform(navigatedShellUrl),
            opts.signal,
          )
          bridge
            .send({
              type: 'evaluate',
              simId: targetSim.id,
              code: `window.location.href = ${JSON.stringify(navigationUrl.toString())}`,
            })
            .catch(() => {})
        }
      } catch (err) {
        console.error(
          `  open failed: ${err instanceof Error ? err.message : String(err)}`,
        )
        await printBridgeFailureDiagnostics(bridge, {
          errorsCommand: `peach get errors 5${simHint}`,
          warningsCommand: `peach get warnings 5${simHint}`,
          requestsCommand: `peach get requests 5${simHint}`,
        })
        peachExit(1)
      }

      if (!fallBackToNewSim && targetSim && navigatedShellUrl) {
        // the navigated page may keep the sim id (restored from session
        // storage) or register a new one, so match by token, never by id.
        const navigatedSim = await waitForSimMatch(
          parsed.wsPort,
          parsed.commandTimeoutMs,
          (sim) =>
            sim.readyState === 'open' &&
            simUsesDriver(sim, driverId, renderer, pinnedHostExecutable) &&
            simMatchesToken(sim),
          { attempts: Math.round(30 * flowTimeoutScale()) },
        )
        if (!navigatedSim) {
          console.error(
            `  timed out waiting for sim ${targetSim.id} to load ${navigatedShellUrl}`,
          )
          await printBridgeFailureDiagnostics(bridge, {
            errorsCommand: `peach get errors 5${simHint}`,
            warningsCommand: `peach get warnings 5${simHint}`,
            requestsCommand: `peach get requests 5${simHint}`,
          })
          peachExit(1)
        }
        targetSim = navigatedSim
        const ready = await waitForSimReady(
          parsed.wsPort,
          parsed.commandTimeoutMs,
          targetSim.id,
          { attempts: Math.round(30 * flowTimeoutScale()), simIdSource: 'flag' },
        )
        if (!ready.bridge) {
          console.error(
            `  timed out waiting for current sim to load target ${ready.failure}`,
          )
          await printBridgeFailureDiagnostics(bridge, {
            errorsCommand: `peach get errors 5${simHint}`,
            warningsCommand: `peach get warnings 5${simHint}`,
            requestsCommand: `peach get requests 5${simHint}`,
          })
          peachExit(1)
        }
        ready.bridge.close()
        saveCurrentSimId(targetSim.id, parsed.wsPort)
        printOpenedSim(
          navigatedShellUrl,
          { ...targetSim, url: navigatedShellUrl },
          'current sim',
          quiet,
          json,
        )
        await maybeDescribeAfterOpen(parsed.wsPort, targetSim.id, args)
        printAgentHints(quiet)
        return { simId: targetSim.id, launched: false }
      }
    } finally {
      bridge.close()
    }
  }

  const configuredBaseUrl = applyPeachConfigToUrl(baseUrl, runtimeConfig)
  const builtShellUrl =
    newSimShellUrl ??
    (await buildShellUrl(shellTarget, configuredBaseUrl, buildShellUrlOpts))
  await awaitStampedExpoSwiftReady(
    builtShellUrl,
    token,
    shellUrlPlatform(builtShellUrl),
    opts.signal,
  )
  const openUrl = withOpenToken(builtShellUrl, token)
  const ownerPid = opts.ownerPid ?? getStableOwnerPid()
  if (!ownerPid) {
    console.error(
      '  could not resolve a stable owning process; refusing unsupervised sim host',
    )
    peachExit(1)
  }
  const driver = getDriver(driverId)
  if (!driver) {
    console.error(`  unknown driver "${driverId}" — run \`peach list --drivers\``)
    peachExit(1)
  }
  const connectWait = resolveDriverConnectWaitOptions()
  opts.signal?.throwIfAborted()
  // the engine applies an ownerless seed to the app its url boots, on ios
  const seededLaunchPermissions =
    driverId === 'playwright' &&
    shellUrlPlatform(builtShellUrl) === 'ios' &&
    getCliRuntime().render_worker_app_load.isAppBootTargetUrl(builtShellUrl)
      ? opts.launchPermissions
      : undefined
  const result = await driver.launch({
    url: openUrl,
    bootScript:
      seededLaunchPermissions &&
      buildPermissionSeedScript({
        appId: null,
        platform: 'ios',
        presets: seededLaunchPermissions,
        grantInstallPermissions: false,
      }),
    // the shell serves the sim page but its WS bridge may have drifted off
    // the shell-port-implied default. inject the bridge this command settled
    // on so the page does not reconnect to a stale world. re-deriving it from
    // the shell URL could name a third port, since a bridge with no lockfile
    // resolves back to the default shell URL and that shell may belong to a
    // live world of its own.
    bridgePort: parsed.wsPort,
    headless: driverHeadless,
    chromium,
    profileId,
    ephemeralProfile,
    cdpPort,
    device: deviceArg,
    ownerPid,
    viewport:
      explicitViewport ??
      (deviceFitBox
        ? {
            // a fractional frame (the 17 Pro bezel is 15.3pt) has to be a whole
            // viewport. the fit pads (stage, menu, shadow) are larger than the
            // old 60pt slack, and the phone was still scaled to about 0.97,
            // which paints the capture root halfway between raster pixels.
            width: Math.ceil(deviceFitBox.width + 120),
            height: Math.ceil(deviceFitBox.height + 140),
          }
        : undefined),
    connectTimeoutMs: connectWait.hostTimeoutMs,
  })
  if (opts.resources) {
    opts.resources.driver = { ...result, driverId }
    opts.resources.launchPermissionsSeeded =
      seededLaunchPermissions !== undefined && result.launched
  }
  opts.signal?.throwIfAborted()
  if (!result.launched) {
    console.error(`  ${driver.name} driver: ${result.message}`)
    peachExit(1)
  }
  const outcome = await waitForSimMatchOrHostExit(
    parsed.wsPort,
    parsed.commandTimeoutMs,
    simMatchesToken,
    result.pid,
    {
      attempts: connectWait.attempts,
      intervalMs: connectWait.intervalMs,
      signal: opts.signal,
      admittedFile: result.admittedFile,
    },
  )
  if (outcome.kind === 'host-exit') {
    printDriverDiagnosticLogTail(result)
    const unserved = readUnservedUrl(result)
    if (unserved) {
      console.error(
        `  nothing serves ${unserved} — start the shell or daemon that owns it, then try again`,
      )
    } else {
      console.error(`  ${driver.name} host crashed — sim is no longer attached`)
    }
    peachExit(1)
  }
  if (outcome.kind === 'timeout') {
    if (result.pid) {
      try {
        process.kill(result.pid, 'SIGTERM')
        console.error(`  closed ${driver.name} host process ${result.pid}`)
      } catch {}
    }
    printDriverDiagnosticLogTail(result)
    console.error(
      `  timed out after ${connectWait.timeoutMs}ms waiting for opened sim to connect`,
    )
    peachExit(1)
  }
  const match = outcome.sim
  if (opts.resources) opts.resources.simId = match.id
  saveCurrentSimId(match.id, parsed.wsPort)
  signalDriverLaunchConnected(result)
  // a sim registers with the bridge as its page boots, before its app has a
  // tree; open returns a sim the next command can drive, as a reused one does.
  // a first dev-server bundle can take as long as the launch itself, so the
  // launch's own connect budget bounds it.
  const ready = await waitForSimReady(parsed.wsPort, parsed.commandTimeoutMs, match.id, {
    intervalMs: connectWait.intervalMs,
    attempts: connectWait.attempts,
    simIdSource: 'flag',
  })
  if (!ready.bridge) {
    console.error(
      `  timed out waiting for opened sim ${match.id} to load ${ready.failure}`,
    )
    const hint = ` --sim ${match.id}`
    const bridge = createBridge(parsed.wsPort, {
      commandTimeoutMs: parsed.commandTimeoutMs,
      simId: match.id,
      simIdSource: 'flag',
    })
    const attached = await bridge
      .listSims()
      .then((sims) => sims.find((sim) => sim.id === match.id)?.readyState ?? 'gone')
      .catch(() => 'unknown')
    console.error(
      `  sim ${match.id} bridge state: ${attached}; host load ${os.loadavg()[0].toFixed(1)} on ${os.cpus().length} cpus (a loaded host slows a cold first bundle past the budget; a sim that is open but never answers has a blocked page)`,
    )
    await printBridgeFailureDiagnostics(bridge, {
      errorsCommand: `peach get errors 5${hint}`,
      warningsCommand: `peach get warnings 5${hint}`,
      requestsCommand: `peach get requests 5${hint}`,
    })
    bridge.close()
    peachExit(1)
  }
  ready.bridge.close()
  printOpenedSim(openUrl, match, `${driver.name} driver`, quiet, json)
  await maybeDescribeAfterOpen(parsed.wsPort, match.id, args)
  printAgentHints(quiet)
  return { simId: match.id, launched: true }
}

async function runUseLikeCommand(args: string[], opts: ControlCommandOptions = {}) {
  const parsed = parseBridgeCliArgs(args, {
    port: opts.port,
    commandTimeoutMs: opts.timeoutMs,
    stripBooleanFlags: ['--force'],
  })
  const force = args.includes('--force')
  const bridge = createBridgeFromParsed(parsed)
  const simHint = parsed.simId ? ` --sim ${parsed.simId}` : ''

  try {
    try {
      const sims = await bridge.listSims()
      const target = resolveTargetSim(sims, parsed.positional[0] || parsed.simId)
      // `use`/`focus` retarget the CLI at a sim — silently grabbing one a
      // human is actively driving is the same footgun `claim` guards against,
      // so honor the lock here too (this command historically did not, which
      // let `peach use <id>` steal the user's live tab).
      // a lease this CLI identity holds is its own target already.
      if (
        target.lockedBy &&
        !target.lockedByMe &&
        target.lockExpiresAt &&
        target.lockExpiresAt > Date.now()
      ) {
        const secs = Math.max(0, Math.round((target.lockExpiresAt - Date.now()) / 1000))
        if (target.lockedByKind === 'user-active') {
          // the active human is interacting with this tab. never steal it,
          // even with --force — mirrors `claim`, which refuses to even
          // report a user-active takeover. open a fresh sim instead.
          console.error(
            `  refused: ${target.id} is locked by the active user (${secs}s) — that's a live human tab`,
          )
          console.error(`  run \`peach open --new\` for a fresh investigation sim`)
          peachExit(1)
        }
        if (!force) {
          // another CLI agent leases it. don't hijack its target silently;
          // a cli lease is short (60s, refreshes per command) so this is
          // usually a real conflict, not a stale lock.
          console.error(
            `  refused: ${target.id} is leased by ${formatLockOwner(target.lockedBy)} (${secs}s)`,
          )
          console.error(
            `  \`peach use ${target.id} --force\` to take it, or \`peach open --new\` for a fresh sim`,
          )
          peachExit(1)
        }
      }
      await bridge.focusSim(target.id)
      saveCurrentSimId(target.id, parsed.wsPort)
      console.log(`  using: ${target.id}`)
    } catch (err) {
      rethrowIfExit(err)
      console.error(`  use failed: ${err instanceof Error ? err.message : String(err)}`)
      await printBridgeFailureDiagnostics(bridge, {
        errorsCommand: `peach get errors 5${simHint}`,
        warningsCommand: `peach get warnings 5${simHint}`,
        requestsCommand: `peach get requests 5${simHint}`,
      })
      peachExit(1)
    }
  } finally {
    bridge.close()
  }
}

export async function runUseCommand(args: string[], opts: ControlCommandOptions = {}) {
  await runUseLikeCommand(args, opts)
}

export async function runClaimCommand(args: string[], opts: ControlCommandOptions = {}) {
  const parsed = parseBridgeCliArgs(args, {
    port: opts.port,
    commandTimeoutMs: opts.timeoutMs,
    stripBooleanFlags: ['--force'],
  })
  const force = args.includes('--force')
  const bridge = createBridgeFromParsed(parsed)

  try {
    try {
      const sims = await bridge.listSims()
      const target = resolveTargetSim(sims, parsed.positional[0] || parsed.simId)
      const priorHolder =
        force &&
        target.lockedBy &&
        !target.lockedByMe &&
        target.lockedByKind !== 'user-active'
          ? target.lockedBy
          : null
      const result = await bridge.claim(target.id, { force })
      saveCurrentSimId(target.id, parsed.wsPort)
      const ttl = Math.max(0, Math.round((result.lockExpiresAt - Date.now()) / 1000))
      const booted = result.bootedCount > 0 ? ` (booted ${result.bootedCount})` : ''
      console.log(`  claimed: ${result.simId} [${ttl}s]${booted}`)
      if (priorHolder) {
        console.log(`  took over from: ${priorHolder}`)
      }
    } catch (err) {
      if (err instanceof BridgeSimLockedError) {
        const secs = Math.max(0, Math.round(err.lock.expiresInMs / 1000))
        console.error(
          `  claim failed: locked by ${formatLockOwner(err.lock.by)} for ${secs}s more`,
        )
        console.error(`  use --force to take it, or \`peach open --new\` for a fresh sim`)
        peachExit(1)
      }
      console.error(`  claim failed: ${err instanceof Error ? err.message : String(err)}`)
      peachExit(1)
    }
  } finally {
    bridge.close()
  }
}

// close many sims at once. fires every close, then polls listSims until the
// whole set is gone or the timeout elapses — far faster than awaiting
// waitForSimGone serially when clearing dozens of leaked sims.
export async function closeSimsBulk(
  bridge: ReturnType<typeof createBridgeFromParsed>,
  wsPort: number,
  commandTimeoutMs: number,
  ids: string[],
  closeOpts: { force?: boolean } = {},
): Promise<{ closed: string[]; remaining: string[]; refused: string[] }> {
  if (ids.length === 0) return { closed: [], remaining: [], refused: [] }
  // a host refusal (a lease taken after the caller listed) leaves the sim and its
  // browser host alone: callers must not terminate a refused sim's host.
  const refused: string[] = []
  await Promise.all(
    ids.map((id) =>
      bridge.closeSim(id, closeOpts).catch((err: unknown) => {
        if (err instanceof BridgeSimLockedError) refused.push(id)
      }),
    ),
  )
  const wanted = new Set(ids.filter((id) => !refused.includes(id)))
  // a closed sim disconnects within a few frames, and a flow waits on this before it exits
  const deadline = Date.now() + 10_000
  for (;;) {
    let stillOpen: string[] = []
    try {
      const probe = createBridge(wsPort, { commandTimeoutMs })
      try {
        const sims = await probe.listSims()
        stillOpen = sims
          .filter((s) => wanted.has(s.id) && s.readyState === 'open')
          .map((s) => s.id)
      } finally {
        probe.close()
      }
    } catch {
      stillOpen = []
    }
    if (stillOpen.length === 0) {
      return { closed: [...wanted], remaining: refused, refused }
    }
    if (Date.now() >= deadline) {
      return {
        closed: [...wanted].filter((id) => !stillOpen.includes(id)),
        remaining: [...stillOpen, ...refused],
        refused,
      }
    }
    await sleep(25)
  }
}

export interface BulkCloseRefusal {
  id: string
  lockedBy: string
  kind: 'cli' | 'user-active'
  expiresInMs: number
}

export interface BulkClosePlan {
  openIds: string[]
  keepId: string | null
  targets: string[]
  staleSavedId: string | null
  missingExplicitKeepId: string | null
  fallbackKeepId: string | null
  refused: BulkCloseRefusal[]
}

// a live lease another cli or the active user holds refuses a close. --force takes
// over another agent's cli lease, the same escape hatch `use --force` offers; a
// `user-active` lease is a live human tab and is never closable, matching
// `claim`, which refuses to report a takeover.
export function closeLeaseRefusal(
  sim: BridgeSimInfo,
  opts: { force?: boolean; now?: number },
): BulkCloseRefusal | null {
  const now = opts.now ?? Date.now()
  const lockedBy = sim.lockedBy
  const expiresAt = sim.lockExpiresAt
  if (!lockedBy || !expiresAt || expiresAt <= now || sim.lockedByMe) return null
  const kind = sim.lockedByKind ?? 'cli'
  if (kind === 'cli' && opts.force) return null
  return { id: sim.id, lockedBy, kind, expiresInMs: Math.max(0, expiresAt - now) }
}

export function planBulkCloseTargets(
  sims: BridgeSimInfo[],
  opts: {
    closeOthers: boolean
    explicitKeepId?: string
    savedKeepId?: string | null
    force?: boolean
    now?: number
  },
): BulkClosePlan {
  const open = sims.filter((sim) => sim.readyState === 'open')
  const openIds = open.map((sim) => sim.id)
  const explicitKeepId = opts.explicitKeepId?.trim() || ''
  const savedKeepId = opts.savedKeepId?.trim() || ''
  const savedIsOpen = savedKeepId ? open.some((sim) => sim.id === savedKeepId) : false
  const staleSavedId = savedKeepId && !savedIsOpen ? savedKeepId : null
  let keepId: string | null = null
  let missingExplicitKeepId: string | null = null
  let fallbackKeepId: string | null = null

  if (opts.closeOthers) {
    if (explicitKeepId) {
      const match = open.find((sim) => sim.id === explicitKeepId)
      if (match) {
        keepId = match.id
      } else {
        missingExplicitKeepId = explicitKeepId
      }
    } else if (savedKeepId && savedIsOpen) {
      keepId = savedKeepId
    } else {
      const fallback = open.find((sim) => sim.isPrimary) ?? open[0] ?? null
      if (fallback) {
        keepId = fallback.id
        if (savedKeepId && !savedIsOpen) fallbackKeepId = fallback.id
      }
    }
  }

  // a sim another agent holds is not ours to close. `use`/`focus`/`claim` all
  // refuse a live lease; bulk close historically did not look at leases at
  // all, so `close --all` silently killed other agents' sims mid-capture.
  const now = opts.now ?? Date.now()
  const refused: BulkCloseRefusal[] = []
  for (const sim of open) {
    if (sim.id === keepId) continue
    const refusal = closeLeaseRefusal(sim, { force: opts.force, now })
    if (refusal) refused.push(refusal)
  }
  const refusedIds = new Set(refused.map((entry) => entry.id))

  return {
    openIds,
    keepId,
    targets: missingExplicitKeepId
      ? []
      : openIds.filter((id) => id !== keepId && !refusedIds.has(id)),
    staleSavedId,
    missingExplicitKeepId,
    fallbackKeepId,
    refused,
  }
}

export async function runCloseCommand(args: string[], opts: ControlCommandOptions = {}) {
  const parsed = parseBridgeCliArgs(args, {
    port: opts.port,
    commandTimeoutMs: opts.timeoutMs,
    stripBooleanFlags: ['--all', '--others', '--force'],
  })
  const bridge = createBridgeFromParsed(parsed)
  const simHint = parsed.simId ? ` --sim ${parsed.simId}` : ''
  const closeAll = args.includes('--all')
  const closeOthers = args.includes('--others')
  const force = args.includes('--force')

  // close resolves its own sim ids before the bridge sees them, so the
  // bridge's pending-open check cannot tell a named sim from a chosen one.
  // refuse here, before any bridge command, when the user named no sim.
  const namedSim = parsed.positional[0] || parsed.simIdSource === 'flag'
  if (!namedSim) {
    try {
      assertNoPendingOpen()
    } catch (err) {
      console.error(`  close failed: ${err instanceof Error ? err.message : String(err)}`)
      bridge.close()
      peachExit(1)
    }
  }

  if (closeAll || closeOthers) {
    try {
      const sims = await bridge.listSims()
      const savedId = readCurrentSimId()
      const explicitKeepId =
        parsed.positional[0] || (parsed.simIdSource === 'flag' ? parsed.simId : undefined)
      // `--others` keeps the explicitly-targeted sim, else the saved/current
      // sim, else primary. if an explicit keep target is gone, abort instead
      // of treating "keep nothing" as permission to close every open sim.
      const plan = planBulkCloseTargets(sims, {
        closeOthers,
        explicitKeepId,
        savedKeepId: savedId,
        force,
      })
      for (const entry of plan.refused) {
        const secs = Math.round(entry.expiresInMs / 1000)
        console.error(
          entry.kind === 'user-active'
            ? `  skipped: ${entry.id} is locked by the active user (${secs}s) — that's a live human tab`
            : `  skipped: ${entry.id} is leased by ${formatLockOwner(entry.lockedBy)} (${secs}s)`,
        )
      }
      if (plan.refused.some((entry) => entry.kind === 'cli') && !force) {
        console.error(`  \`peach close --all --force\` to close leased sims too`)
      }
      if (plan.staleSavedId) {
        clearCurrentSimId()
      }
      if (plan.fallbackKeepId) {
        saveCurrentSimId(plan.fallbackKeepId, parsed.wsPort)
        console.log(
          `  saved sim ${plan.staleSavedId} is gone — keeping primary ${plan.fallbackKeepId}`,
        )
      }
      if (plan.missingExplicitKeepId) {
        console.error(
          `  close failed: keep sim ${plan.missingExplicitKeepId} is not connected; not closing other sims`,
        )
        peachExit(1)
      }
      if (plan.targets.length === 0) {
        console.log(
          plan.keepId
            ? `  nothing to close — only the kept sim ${plan.keepId} is connected`
            : plan.refused.length > 0
              ? `  nothing to close — every other connected sim is leased by someone else`
              : plan.staleSavedId
                ? `  nothing to close — no sims connected (cleared stale current sim ${plan.staleSavedId})`
                : '  nothing to close — no sims connected',
        )
        return
      }
      const result = await closeSimsBulk(
        bridge,
        parsed.wsPort,
        parsed.commandTimeoutMs,
        plan.targets,
        { force },
      )
      await terminatePlaywrightHostsForSims(
        sims,
        plan.targets.filter((id) => !result.refused.includes(id)),
      )
      // saved current sim may have just been closed — repoint or clear it.
      const nextSavedId = readCurrentSimId()
      if (nextSavedId && result.closed.includes(nextSavedId)) {
        if (plan.keepId) saveCurrentSimId(plan.keepId, parsed.wsPort)
        else clearCurrentSimId()
      }
      const summary = `  closed ${result.closed.length} sim(s)${
        plan.keepId ? ` (kept ${plan.keepId})` : ''
      }`
      console.log(summary)
      if (result.remaining.length > 0) {
        console.error(`  close failed: still connected: ${result.remaining.join(', ')}`)
        peachExit(1)
      }
    } catch (err) {
      rethrowIfExit(err)
      console.error(`  close failed: ${err instanceof Error ? err.message : String(err)}`)
      peachExit(1)
    } finally {
      bridge.close()
    }
    return
  }

  try {
    try {
      const sims = await bridge.listSims()
      const target = resolveTargetSim(sims, parsed.positional[0] || parsed.simId)
      const fallbackTarget = sims.find(
        (sim) => sim.id !== target.id && sim.readyState === 'open',
      )
      const refusal = closeLeaseRefusal(target, { force })
      if (refusal) {
        const secs = Math.round(refusal.expiresInMs / 1000)
        console.error(
          `  close failed: ${refusal.id} is ${
            refusal.kind === 'user-active'
              ? `locked by the active user (${secs}s)`
              : `leased by ${formatLockOwner(refusal.lockedBy)} (${secs}s)`
          }`,
        )
        if (refusal.kind === 'cli') {
          console.error(`  \`peach close ${refusal.id} --force\` to close it anyway`)
        }
        peachExit(1)
      }
      await bridge.closeSim(target.id, { force })
      const closed = await waitForSimGone(
        parsed.wsPort,
        parsed.commandTimeoutMs,
        target.id,
      )
      if (!closed) {
        await terminatePlaywrightHostsForSims(sims, [target.id])
        console.error(`  close failed: ${target.id} is still connected`)
        peachExit(1)
      }
      await terminatePlaywrightHostsForSims(sims, [target.id])
      if (readCurrentSimId() === target.id) {
        if (fallbackTarget) saveCurrentSimId(fallbackTarget.id, parsed.wsPort)
        else clearCurrentSimId()
      }
      console.log(`  closed: ${target.id}`)
    } catch (err) {
      rethrowIfExit(err)
      console.error(`  close failed: ${err instanceof Error ? err.message : String(err)}`)
      // `all` and `others` are flags, never sim ids.
      const word = parsed.positional[0]
      if (word === 'all' || word === 'others') {
        console.error(
          `  to close ${word === 'all' ? 'every' : 'every other'} sim: peach close --${word}`,
        )
        peachExit(1)
      }
      await printBridgeFailureDiagnostics(bridge, {
        errorsCommand: `peach get errors 5${simHint}`,
        warningsCommand: `peach get warnings 5${simHint}`,
        requestsCommand: `peach get requests 5${simHint}`,
      })
      peachExit(1)
    }
  } finally {
    bridge.close()
  }
}

export {
  buildShellUrl,
  looksLikeShellPathTarget,
  looksLikeSootsimUrl,
  resolveAppProjectForBundleUrl,
  resolveShellBaseUrlForBridgePort,
  shellUrlPlatform,
  shouldResolveBundleTargetInCli,
  type BuildShellUrlOptions,
}
export { resolveDefaultShellBaseUrl } from './shell-url'
