export const PREVIEW_TEXT_MAX_LENGTH = 50000;

const TEXT_FILE_EXTENSIONS = [
  ".json",
  ".jsonl",
  ".txt",
  ".csv",
  ".tsv",
  ".xml",
  ".md",
  ".yaml",
  ".yml",
];
const IMAGE_FILE_EXTENSIONS = [
  ".jpg",
  ".jpeg",
  ".png",
  ".gif",
  ".bmp",
  ".webp",
  ".svg",
];
const VIDEO_FILE_EXTENSIONS = [".mp4", ".webm", ".ogg", ".mov", ".avi"];
const AUDIO_FILE_EXTENSIONS = [".mp3", ".wav", ".ogg", ".aac", ".flac", ".m4a"];

export type PreviewFileType = "text" | "image" | "video" | "audio";

export const resolvePreviewFileType = (fileName?: string): PreviewFileType | null => {
  const lowerName = (fileName || "").toLowerCase();
  if (TEXT_FILE_EXTENSIONS.some((ext) => lowerName.endsWith(ext))) {
    return "text";
  }
  if (IMAGE_FILE_EXTENSIONS.some((ext) => lowerName.endsWith(ext))) {
    return "image";
  }
  if (VIDEO_FILE_EXTENSIONS.some((ext) => lowerName.endsWith(ext))) {
    return "video";
  }
  if (AUDIO_FILE_EXTENSIONS.some((ext) => lowerName.endsWith(ext))) {
    return "audio";
  }
  return null;
};

export const truncatePreviewText = (text: string, maxLength = PREVIEW_TEXT_MAX_LENGTH) => {
  if (text.length > maxLength) {
    return `${text.slice(0, maxLength)}\n\n... (内容过长，仅显示前 ${maxLength} 字符)`;
  }
  return text;
};
