/**
 * 文件 / 产物图标统一 lookup
 *
 * - 同一份资源被 ChatInput 的「附件 chip」和 ChatMessage 的「用户消息附件卡 / 产物卡」共用
 * - 优先级（getFileTypeIcon）：file.iconSrc → file.iconType → 文件扩展名 → fallback (pdf)
 *
 * 业务类型字典（iconType / 显式语义）：
 *   pdf | code | xmind | pe | conversation | image | batch-report | document
 *   knowledge | strategy | webpage | table | feishu | feishu-card | feishu-sheet
 *
 * 扩展名兜底字典：
 *   .pdf → pdf
 *   .png/.jpg/.jpeg/.gif/.webp/.svg → image
 *   .doc/.docx/.txt/.md → document
 *   .xls/.xlsx/.csv → table
 *   .xmind → xmind
 *   .js/.ts/.jsx/.tsx/.py/.json/.html/.css → code
 */

import pdfIcon from './pdf.png';
import codeIcon from './code.png';
import peIcon from './pe.png';
import xmindIcon from './xmind.png';
import conversationIcon from './conversation.png';
import imageIcon from './image.png';
import batchReportIcon from './batch-report.png';
import documentIcon from './document.png';
import knowledgeIcon from './knowledge.png';
import strategyIcon from './strategy.png';
import webpageIcon from './webpage.png';
import tableIcon from './table.png';
import feishuIcon from './feishu.png';
import feishuCardIcon from './feishu-card.png';
import feishuSheetIcon from './feishu-sheet.png';

/* 业务语义 → 图标资源（用于产物 / 自定义场景显式指定） */
export const FILE_TYPE_ICONS = {
  pdf: pdfIcon,
  code: codeIcon,
  pe: peIcon,
  xmind: xmindIcon,
  conversation: conversationIcon,
  image: imageIcon,
  'batch-report': batchReportIcon,
  document: documentIcon,
  knowledge: knowledgeIcon,
  strategy: strategyIcon,
  webpage: webpageIcon,
  table: tableIcon,
  feishu: feishuIcon,
  'feishu-card': feishuCardIcon,
  'feishu-sheet': feishuSheetIcon,
};

/* 文件扩展名 → 业务语义类型（兜底使用） */
const EXT_TO_TYPE = {
  pdf: 'pdf',
  png: 'image',
  jpg: 'image',
  jpeg: 'image',
  gif: 'image',
  webp: 'image',
  svg: 'image',
  doc: 'document',
  docx: 'document',
  txt: 'document',
  md: 'document',
  xls: 'table',
  xlsx: 'table',
  csv: 'table',
  xmind: 'xmind',
  js: 'code',
  ts: 'code',
  jsx: 'code',
  tsx: 'code',
  py: 'code',
  json: 'code',
  html: 'code',
  css: 'code',
};

export const FILE_TYPE_FALLBACK = pdfIcon;

/**
 * 统一文件图标解析
 * @param {object|string} fileOrName - 文件对象 { name, iconSrc?, iconType? } 或裸文件名字符串
 * @returns {string} 图标资源 URL
 */
export function getFileTypeIcon(fileOrName) {
  if (!fileOrName) return FILE_TYPE_FALLBACK;
  if (typeof fileOrName === 'string') {
    return resolveByName(fileOrName);
  }
  if (fileOrName.iconSrc) return fileOrName.iconSrc;
  if (fileOrName.iconType && FILE_TYPE_ICONS[fileOrName.iconType]) {
    return FILE_TYPE_ICONS[fileOrName.iconType];
  }
  return resolveByName(fileOrName.name);
}

function resolveByName(name) {
  const ext = String(name ?? '').split('.').pop()?.toLowerCase();
  const type = EXT_TO_TYPE[ext];
  return (type && FILE_TYPE_ICONS[type]) || FILE_TYPE_FALLBACK;
}
