export async function withPager(fn: () => Promise<void> | void): Promise<void> {
  if (!process.stdout.isTTY) {
    await fn()
    return
  }

  const lines: string[] = []
  const originalLog = console.log

  console.log = (...args: unknown[]) => {
    lines.push(args.map(a => typeof a === 'string' ? a : String(a)).join(' '))
  }

  try {
    await fn()
  } finally {
    console.log = originalLog
  }

  if (lines.length === 0) return

  const text = lines.join('\n') + '\n'
  const rows = process.stdout.rows || 24
  const lineCount = text.split('\n').length - 1

  if (lineCount > rows) {
    Bun.spawnSync(['less', '-R'], {
      stdin: Buffer.from(text),
      stdout: 'inherit',
      stderr: 'inherit',
    })
  } else {
    process.stdout.write(text)
  }
}
