function splitExtension(fileName: string): { base: string; ext: string } {
  const safe = fileName.trim();
  const lastDot = safe.lastIndexOf(".");
  if (lastDot <= 0 || lastDot === safe.length - 1) {
    return { base: safe, ext: "" };
  }
  return { base: safe.slice(0, lastDot), ext: safe.slice(lastDot) };
}

export function makeUniqueTitle(baseTitle: string, existing: Set<string>): string {
  const base = baseTitle.trim() || "无标题";
  if (!existing.has(base)) {
    existing.add(base);
    return base;
  }
  const first = `${base} 副本`;
  if (!existing.has(first)) {
    existing.add(first);
    return first;
  }
  for (let i = 2; i < 1000; i += 1) {
    const candidate = `${base} 副本 ${i}`;
    if (!existing.has(candidate)) {
      existing.add(candidate);
      return candidate;
    }
  }
  const fallback = `${base} 副本 ${Date.now()}`;
  existing.add(fallback);
  return fallback;
}

export function makeUniqueFileName(fileName: string, existing: Set<string>): string {
  const safe = fileName.trim() || "附件";
  if (!existing.has(safe)) {
    existing.add(safe);
    return safe;
  }
  const { base, ext } = splitExtension(safe);
  const first = `${base} 副本${ext}`;
  if (!existing.has(first)) {
    existing.add(first);
    return first;
  }
  for (let i = 2; i < 1000; i += 1) {
    const candidate = `${base} 副本 ${i}${ext}`;
    if (!existing.has(candidate)) {
      existing.add(candidate);
      return candidate;
    }
  }
  const fallback = `${base} 副本 ${Date.now()}${ext}`;
  existing.add(fallback);
  return fallback;
}

