/**
 * Runtime helpers shared by TUI pages.
 *
 * The CLI can run in multiple environments:
 * - Node/Bun (terminal UI)
 * - Browser (storybook-like/demo harness)
 *
 * These helpers provide a consistent way to detect Node-like runtimes.
 */

type RuntimeProcess = Pick<NodeJS.Process, 'cwd' | 'versions'>

type RuntimeGlobals = typeof globalThis & {
  process?: RuntimeProcess
}

function runtimeGlobals(): RuntimeGlobals {
  return globalThis as RuntimeGlobals
}

export function isNodeLike(): boolean {
  const p = runtimeGlobals().process
  const hasNodeVersion = typeof p?.versions?.node === 'string'
  const hasBunVersion = typeof p?.versions?.bun === 'string'
  return (
    !!p && (hasNodeVersion || hasBunVersion) && typeof p?.cwd === 'function'
  )
}

export function getProcessCwd(): string {
  try {
    const p = runtimeGlobals().process
    const cwd = typeof p?.cwd === 'function' ? String(p.cwd()) : ''
    return cwd || '/'
  } catch {
    return '/'
  }
}
