/** Mirror `be0/src/initiative_db/backup_naming.official_form_pdf_backup_zip_path` (basename only). */

const EMAIL_RE = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/;

function sanitizeFilenameSegment(name: string): string {
  const cleaned = name
    .replace(/[/\\]/g, "_")
    .replace(/\s+/g, "_")
    .replace(/[\u0000-\u001f]/g, "")
    .trim()
    .slice(0, 200);
  return cleaned || "file";
}

function extractContactEmail(text: string): string {
  const raw = text.trim();
  if (!raw) return "";
  const m = raw.match(EMAIL_RE);
  return m ? m[0] : raw;
}

/**
 * Download / backup display name: `{Tên_sáng_kiến}_{tên_tác_giả}_{email_liên_hệ}.pdf`
 * from « TRANG BÌA » (same keys as `official_to_data_blank`).
 */
export function buildOfficialFormPdfFileName(official: Record<string, unknown>): string {
  const biaRaw = official["TRANG BÌA"];
  if (!biaRaw || typeof biaRaw !== "object") {
    return "Ten_sang_kien_tac_gia_email_lien_he.pdf";
  }
  const bia = biaRaw as Record<string, unknown>;
  const ten = String(bia["Tên sáng kiến (Tiếng Việt)"] ?? "").trim();
  const tac = String(bia["Tác giả/nhóm tác giả sáng kiến"] ?? "").trim();
  const lien = String(bia["Thông tin liên hệ (Điện thoại, Email)"] ?? "").trim();
  const email = extractContactEmail(lien);
  if (!ten && !tac && !email) {
    return "Ten_sang_kien_tac_gia_email_lien_he.pdf";
  }
  const partTen = ten ? sanitizeFilenameSegment(ten) : "Ten_sang_kien";
  const partTac = tac ? sanitizeFilenameSegment(tac) : "tac_gia";
  const partMail = email ? sanitizeFilenameSegment(email) : "email_lien_he";
  let stem = `${partTen}_${partTac}_${partMail}`;
  if (stem.length > 180) {
    stem = stem.slice(0, 180);
  }
  return `${stem}.pdf`;
}
