/**
 * CLI argument parsing for the DimCode TUI.
 *
 * Keep this module side-effect free so it can be tested / reused.
 */

export type CliArgs = Readonly<{
  cols: number
  rows: number
  sizeLocked: boolean
  app: string
  initialRoute: string
  recordPath: string | null
  replayPath: string | null
  snapshotPath: string | null
  enableMouse: boolean
  altScreen: boolean
  approvals: 'auto' | 'normal' | 'strict' | null
  debug: boolean
}>

type StdoutLike
  = | Readonly<{ columns?: number, rows?: number }>
    | null
    | undefined

export function isHelpRequested(argv: readonly string[]): boolean {
  return argv.includes('-h') || argv.includes('--help')
}

export function getHelpText(): string {
  return [
    'Usage:',
    '  dim                              Interactive TUI',
    '  dim [--cwd dir] [--session id] "prompt"',
    '                                   One-shot execution (stdout, tools auto-approved)',
    '  dim auth [provider]              Authenticate provider (next-api-oauth)',
    '  dim version                      Print version info',
    '  dim upgrade [version]            Upgrade CLI',
    '  dim acp                          Start ACP server for editor integrations',
    '',
    'Options:',
    '  --approvals auto|normal|strict   Tool approval mode (default: normal)',
    '  --auto-approve, --yes, -y        Shorthand for --approvals all',
    '  --cols N --rows N                Terminal size override',
    '  --no-mouse                       Disable mouse support',
    '  --no-alt-screen                  Disable alternate screen',
    '  --debug                          Enable debug logging',
    '  -h, --help                       Show this help',
    '',
    'Notes:',
    '  - Interactive TUI defaults to --approvals auto (prompts for risky tools).',
    '  - Use --approvals auto (or -y/--auto-approve) to auto-approve all tools.',
    '  - Auto-update is enabled by default (set DIMCODE_DISABLE_AUTOUPDATE=1 to disable).',
  ].join('\n')
}

export function parseCliArgs(
  argv: readonly string[],
  opts?: Readonly<{ stdout?: StdoutLike }>,
): CliArgs {
  const stdout = opts?.stdout
  const defaultsCols = Number.isFinite(stdout?.columns)
    ? Number(stdout?.columns)
    : 80
  const defaultsRows = Number.isFinite(stdout?.rows) ? Number(stdout?.rows) : 24

  let cols = defaultsCols
  let rows = defaultsRows
  let colsLocked = false
  let rowsLocked = false
  let app = 'dim'
  let initialRoute = 'home'
  let recordPath: string | null = null
  let replayPath: string | null = null
  let snapshotPath: string | null = null
  let enableMouse = true
  let altScreen = true
  let approvals: 'auto' | 'normal' | 'strict' | null = null
  let debug = false

  let i = 0
  const readArgValue = (): string | undefined => {
    if (i + 1 >= argv.length)
      return undefined
    i += 1
    return argv[i]
  }

  for (; i < argv.length; i++) {
    const a = argv[i]
    if (a === '--cols') {
      cols = Number.parseInt(readArgValue() ?? '', 10)
      colsLocked = true
    }
    else if (a === '--rows') {
      rows = Number.parseInt(readArgValue() ?? '', 10)
      rowsLocked = true
    }
    else if (a === '--app' || a === '--example') {
      app = String(readArgValue() ?? app)
    }
    else if (a === '--route' || a === '--initial-route') {
      initialRoute = String(readArgValue() ?? initialRoute)
    }
    else if (a === '--approvals' || a === '--approval') {
      const v = String(readArgValue() ?? '')
        .trim()
        .toLowerCase()
      if (
        v === 'auto'
        || v === 'all'
        || v === 'on'
        || v === 'yes'
        || v === 'true'
        || v === '1'
      ) {
        approvals = 'auto'
      }
      else if (v === 'normal' || v === 'default') {
        approvals = 'normal'
      }
      else if (v === 'strict' || v === 'manual') {
        approvals = 'strict'
      }
    }
    else if (a === '--auto-approve' || a === '--yes' || a === '-y') {
      approvals = 'auto'
    }
    else if (a === '--record') {
      recordPath = readArgValue() ?? null
    }
    else if (a === '--replay') {
      replayPath = readArgValue() ?? null
    }
    else if (a === '--snapshot') {
      snapshotPath = readArgValue() ?? null
    }
    else if (a === '--no-mouse') {
      enableMouse = false
    }
    else if (a === '--no-alt-screen') {
      altScreen = false
    }
    else if (a === '--debug') {
      debug = true
    }
  }

  cols = Math.max(10, Math.floor(cols || defaultsCols))
  rows = Math.max(5, Math.floor(rows || defaultsRows))

  return {
    cols,
    rows,
    sizeLocked: colsLocked || rowsLocked,
    app,
    initialRoute,
    recordPath,
    replayPath,
    snapshotPath,
    enableMouse,
    altScreen,
    approvals,
    debug,
  }
}
