const unsafeFilenameCharacters = /[<>:"/\\|?*\u0000-\u001f\u007f]/g;
const controlCharacters = /[\r\n]/g;

function safeFilename(value: string): string {
  const cleaned = value
    .replace(controlCharacters, "")
    .replace(unsafeFilenameCharacters, "_")
    .replace(/^\.+/, "")
    .trim()
    .slice(0, 180);
  return cleaned || "download";
}

function decodeFilenameStar(value: string): string | null {
  const match = value.match(/^UTF-8''(.+)$/i);
  if (!match) return null;
  try {
    return decodeURIComponent(match[1]);
  } catch {
    return null;
  }
}

export function parseContentDispositionFilename(
  header: string | null,
  fallback: string,
): string {
  if (!header) return safeFilename(fallback);
  const star = header.match(/(?:^|;)\s*filename\*\s*=\s*([^;]+)/i)?.[1]?.trim();
  if (star) {
    const decoded = decodeFilenameStar(star.replace(/^"|"$/g, ""));
    if (decoded) return safeFilename(decoded);
  }
  const plain = header.match(/(?:^|;)\s*filename\s*=\s*(?:"([^"]*)"|([^;]*))/i);
  const value = plain?.[1] ?? plain?.[2]?.trim();
  return safeFilename(value || fallback);
}

export function suggestedNameFromFile(file: File): string {
  const index = file.name.lastIndexOf(".");
  return (index > 0 ? file.name.slice(0, index) : file.name).trim();
}

export const ACCEPTED_DOCUMENT_EXTENSIONS = [".doc", ".docx", ".pdf", ".xls", ".xlsx"] as const;

export function validateSelectedFile(file: File): string | null {
  if (file.size === 0) return "不能选择空文件";
  const lower = file.name.toLowerCase();
  if (!ACCEPTED_DOCUMENT_EXTENSIONS.some((extension) => lower.endsWith(extension))) {
    return "请选择 DOC、DOCX、PDF、XLS 或 XLSX 文件";
  }
  return null;
}
