import { BUILTIN_MODELS } from '@/lib/models'

/** Format token count with k suffix */
export function formatTokens(n: number): string {
  if (n >= 1000) return `${(n / 1000).toFixed(1)}k`
  return String(n)
}

/** Format turn elapsed seconds → "12s" / "2m 5s" */
export function formatTurnElapsed(seconds: number): string {
  if (seconds < 60) return `${seconds}s`
  const m = Math.floor(seconds / 60)
  const s = seconds % 60
  return `${m}m ${s}s`
}

/** Extract domain from URL (fallback to raw string on failure) */
export function getDomain(url: string): string {
  try {
    return new URL(url).hostname.replace(/^www\./, '')
  } catch {
    return url
  }
}

/** Get display-friendly tool name */
export function getToolDisplayName(name: string): string {
  switch (name) {
    case 'WebSearch': return 'Web Search'
    case 'WebFetch': return 'Web Fetch'
    case 'ToolSearch': return 'Tool Search'
    case 'NotebookEdit': return 'Notebook Edit'
    default: return name
  }
}

/** Format a model id into a human-readable label */
export function formatModel(model: string | undefined | null): string {
  if (!model) return 'Claude Sonnet 4.6'
  const found = BUILTIN_MODELS.find((o) => o.id === model)
  if (found) return found.label
  // Fallback: prettify the model ID
  if (model.includes('opus')) return 'Claude Opus 4.6'
  if (model.includes('haiku')) return 'Claude Haiku 4.5'
  if (model.includes('claude')) return 'Claude Sonnet 4.6'
  return model
}

/** Short model name for the toolbar pill (e.g. "Sonnet 4.6" instead of "Claude Sonnet 4.6") */
export function formatModelShort(model: string): string {
  const full = formatModel(model)
  return full.replace(/^Claude\s+/, '')
}

/** Tool summary shown in the tool card header (file path / command / pattern / query) */
export function getToolSummary(name: string, input: Record<string, unknown>): string {
  switch (name) {
    // SDK built-in tools (PascalCase)
    case 'Read': return String(input.file_path || '')
    case 'Write': return String(input.file_path || '')
    case 'Edit': return String(input.file_path || '')
    case 'Bash': return String(input.command || '').slice(0, 80)
    case 'Glob': return String(input.pattern || '')
    case 'Grep': return String(input.pattern || '').slice(0, 60)
    case 'Agent': return String(input.description || '')
    case 'WebFetch': return String(input.url || '').slice(0, 80)
    case 'WebSearch': return String(input.query || '').slice(0, 80)
    case 'ToolSearch': return String(input.query || '').slice(0, 80)
    case 'NotebookEdit': return String(input.file_path || '')
    case 'Skill': return String(input.skill || '')
    // Custom tools (snake_case, legacy)
    case 'read_file': return String(input.path || '')
    case 'write_file': return String(input.path || '')
    case 'list_directory': return String(input.path || '.')
    case 'run_command': return String(input.command || '').slice(0, 60)
    case 'search_files': return String(input.pattern || '')
    case 'search_content': return String(input.pattern || '')
    case 'delegate_to_agent': return `agent:${input.agent_id || '?'} — ${String(input.task || '').slice(0, 40)}`
    case 'browser_navigate': return String(input.url || '')
    case 'browser_click': return `click ${input.selector || ''}`
    case 'browser_type': return `type into ${input.selector || ''}`
    case 'browser_screenshot': return 'screenshot'
    case 'browser_evaluate': return String(input.expression || '').slice(0, 50)
    default:
      if (name.startsWith('browser_')) return name.replace('browser_', '')
      return ''
  }
}

/**
 * Get a detailed parameter preview shown inline while the tool is executing.
 * Returns null if no meaningful preview can be generated.
 */
export function getToolParamPreview(name: string, input: Record<string, unknown>): string | null {
  switch (name) {
    case 'Bash':
    case 'run_command': {
      const cmd = String(input.command || '')
      return cmd ? cmd.slice(0, 500) : null
    }
    case 'Write':
    case 'write_file': {
      const content = String(input.content || '')
      if (!content) return null
      const lines = content.split('\n')
      const preview = lines.slice(0, 8).join('\n')
      const suffix = lines.length > 8 ? `\n... (+${lines.length - 8} more lines)` : ''
      return `→ ${input.file_path || input.path || 'file'}\n${preview}${suffix}`
    }
    case 'Edit': {
      const oldStr = String(input.old_string || '').slice(0, 100)
      const newStr = String(input.new_string || '').slice(0, 100)
      if (!oldStr && !newStr) return null
      return `→ ${input.file_path || input.path || 'file'}\n- ${oldStr.split('\n')[0]}\n+ ${newStr.split('\n')[0]}`
    }
    // Read, WebSearch, WebFetch, Glob, Grep — summary in header is sufficient,
    // no need for duplicate preview panel
    default:
      return null
  }
}
