import chalk from 'chalk'
import { formatAuditLine, listAuditEntries } from '../../services/audit/audit.js'
import type { LocalCommandCall } from '../../types/command.js'

const DEFAULT_LIMIT = 30
const MAX_LIMIT = 500

function parseLimit(args: string): number {
  const trimmed = args.trim()
  if (!trimmed) return DEFAULT_LIMIT
  const n = parseInt(trimmed, 10)
  if (!Number.isFinite(n) || n <= 0) return DEFAULT_LIMIT
  return Math.min(n, MAX_LIMIT)
}

export const call: LocalCommandCall = async (args: string) => {
  const limit = parseLimit(args)
  const entries = await listAuditEntries(limit)

  if (entries.length === 0) {
    return {
      type: 'text',
      value: 'No audit entries yet. Entries accumulate as tools are invoked.',
    }
  }

  const header = `Showing ${entries.length} most recent audit ${entries.length === 1 ? 'entry' : 'entries'}:`
  const body = entries.map((e) => '  ' + formatAuditLine(e)).join('\n')
  return { type: 'text', value: chalk.dim(`${header}\n${body}`) }
}
