export type TopLevelSubcommand
  = | Readonly<{ kind: 'version' }>
    | Readonly<{ kind: 'upgrade', argv: readonly string[] }>
    | Readonly<{ kind: 'acp', argv: readonly string[] }>
    | Readonly<{ kind: 'auth', argv: readonly string[] }>
    | Readonly<{ kind: 'legacy_exec', argv: readonly string[] }>
    | Readonly<{ kind: 'prompt', argv: readonly string[] }>
    | Readonly<{ kind: 'none', argv: readonly string[] }>

const ONE_SHOT_FLAGS = new Set([
  '-c',
  '-cwd',
  '--cwd',
  '--chdir',
  '-s',
  '--session',
])

function isOneShotPromptArgv(argv: readonly string[]): boolean {
  let sawOneShotFlag = false
  for (let i = 0; i < argv.length; i++) {
    const arg = String(argv[i] ?? '').trim()
    if (!arg)
      continue
    if (arg === '--')
      return true
    if (arg.startsWith('-cwd=')) {
      sawOneShotFlag = true
      continue
    }
    if (ONE_SHOT_FLAGS.has(arg)) {
      sawOneShotFlag = true
      i += 1
      continue
    }
    if (arg.startsWith('-'))
      return false
    return true
  }
  return sawOneShotFlag
}

export function resolveTopLevelSubcommand(
  argv: readonly string[],
): TopLevelSubcommand {
  const sub = String(argv[0] ?? '')
    .trim()
    .toLowerCase()
  if (sub === 'version' || sub === '--version' || sub === '-v')
    return { kind: 'version' }
  if (sub === 'upgrade' || sub === 'update')
    return { kind: 'upgrade', argv: argv.slice(1) }
  if (sub === 'acp')
    return { kind: 'acp', argv: argv.slice(1) }
  if (sub === 'auth')
    return { kind: 'auth', argv: argv.slice(1) }
  if (sub === 'exec' || sub === 'e')
    return { kind: 'legacy_exec', argv: argv.slice(1) }
  if (isOneShotPromptArgv(argv))
    return { kind: 'prompt', argv }
  return { kind: 'none', argv }
}
