import chalk from 'chalk'
import { getBudgetConfig, getTodayUsdSpend } from '../../cost-tracker.js'
import type { LocalCommandCall } from '../../types/command.js'
import { formatBudgetLine, parseBudgetSpec } from '../../utils/budget.js'
import { saveGlobalConfig } from '../../utils/config.js'

function usage(): string {
  return [
    'Usage:',
    '  /budget                 Show current budget + session spend',
    '  /budget set $5          Set daily soft limit to $5',
    '  /budget set $5/day      (alternative spelling)',
    '  /budget clear           Remove the daily budget',
  ].join('\n')
}

export const call: LocalCommandCall = async (args: string) => {
  const trimmed = args.trim()
  const todaySpend = getTodayUsdSpend()

  if (trimmed === '') {
    const line = formatBudgetLine(getBudgetConfig(), todaySpend)
    return { type: 'text', value: chalk.dim(`Daily budget: ${line}`) }
  }

  const tokens = trimmed.split(/\s+/)
  const verb = tokens[0]?.toLowerCase()

  if (verb === 'clear' || verb === 'off' || verb === 'none') {
    saveGlobalConfig((c) => ({ ...c, dailyBudgetUSD: undefined }))
    return { type: 'text', value: 'Daily budget cleared.' }
  }

  if (verb === 'set') {
    const spec = tokens.slice(1).join(' ')
    if (!spec) {
      return {
        type: 'text',
        value: `Missing amount. ${usage()}`,
      }
    }
    const parsed = parseBudgetSpec(spec)
    if (parsed === undefined) {
      return {
        type: 'text',
        value: `Could not parse "${spec}" as a budget amount.\n${usage()}`,
      }
    }
    if (parsed === null) {
      saveGlobalConfig((c) => ({ ...c, dailyBudgetUSD: undefined }))
      return { type: 'text', value: 'Daily budget cleared.' }
    }
    saveGlobalConfig((c) => ({ ...c, dailyBudgetUSD: parsed.dailyLimitUSD }))
    const line = formatBudgetLine(parsed, todaySpend)
    return {
      type: 'text',
      value: `Daily budget set. ${line}`,
    }
  }

  // A bare amount is shorthand for `set <amount>`
  const parsed = parseBudgetSpec(trimmed)
  if (parsed !== undefined) {
    if (parsed === null) {
      saveGlobalConfig((c) => ({ ...c, dailyBudgetUSD: undefined }))
      return { type: 'text', value: 'Daily budget cleared.' }
    }
    saveGlobalConfig((c) => ({ ...c, dailyBudgetUSD: parsed.dailyLimitUSD }))
    const line = formatBudgetLine(parsed, todaySpend)
    return { type: 'text', value: `Daily budget set. ${line}` }
  }

  return { type: 'text', value: usage() }
}
