export type ToolSemantic =
  | 'ask_user'
  | 'delegate'
  | 'edit_like'
  | 'exec_like'
  | 'fetch_like'
  | 'other'
  | 'read_like'
  | 'search_like'
  | 'write_like'

const TOOL_ALIAS_MAP: Record<string, string> = {
  ask_user: 'ask-user',
  askuserquestion: 'ask-user',
  bash: 'shell',
  edit: 'edit-workspace',
  contentsearch: 'content-search',
  exec: 'shell',
  glob: 'workspace-search',
  grep: 'content-search',
  read: 'read-file',
  websearch: 'web-search',
  webfetch: 'fetch-url',
  write: 'write-workspace',
}

function normalizeText(value: unknown): string {
  return String(value ?? '').trim().toLowerCase()
}

export function canonicalToolName(rawName: unknown): string {
  const normalized = normalizeText(rawName)
  if (!normalized)
    return ''
  return TOOL_ALIAS_MAP[normalized] ?? normalized
}

export function toolSemantic(rawName: unknown): ToolSemantic {
  switch (canonicalToolName(rawName)) {
    case 'ask-user':
      return 'ask_user'
    case 'delegate_tasks':
      return 'delegate'
    case 'edit-workspace':
    case 'multiedit-workspace':
      return 'edit_like'
    case 'shell':
      return 'exec_like'
    case 'fetch-url':
      return 'fetch_like'
    case 'read-file':
    case 'read-file-range':
      return 'read_like'
    case 'content-search':
    case 'workspace-search':
    case 'web-search':
      return 'search_like'
    case 'write-artifact':
    case 'write-scratch':
    case 'write-workspace':
    case 'write-workspace-batch':
      return 'write_like'
    default:
      return 'other'
  }
}

export function toolDisplayLabel(rawName: unknown): string {
  return canonicalToolName(rawName)
}

export function isAskUserToolName(rawName: unknown): boolean {
  return toolSemantic(rawName) === 'ask_user'
}

export function isDelegateToolName(rawName: unknown): boolean {
  return toolSemantic(rawName) === 'delegate'
}

export function isEditLikeToolName(rawName: unknown): boolean {
  return toolSemantic(rawName) === 'edit_like'
}

export function isExecLikeToolName(rawName: unknown): boolean {
  return toolSemantic(rawName) === 'exec_like'
}

export function isFetchLikeToolName(rawName: unknown): boolean {
  return toolSemantic(rawName) === 'fetch_like'
}

export function isReadLikeToolName(rawName: unknown): boolean {
  return toolSemantic(rawName) === 'read_like'
}

export function isSearchLikeToolName(rawName: unknown): boolean {
  return toolSemantic(rawName) === 'search_like'
}

export function isWriteLikeToolName(rawName: unknown): boolean {
  return toolSemantic(rawName) === 'write_like'
}
