"""Naming helpers for admin application backup downloads (no heavy deps)."""

from __future__ import annotations

import re
import unicodedata
from typing import Any, Dict, Optional

_TRANG_BIA_TEN_SK = "Tên sáng kiến (Tiếng Việt)"
_TRANG_BIA_TAC_GIA = "Tác giả/nhóm tác giả sáng kiến"
_TRANG_BIA_LIEN_HE = "Thông tin liên hệ (Điện thoại, Email)"
_EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")


def _sanitize_filename(name: str) -> str:
    """Match ``src.minio.storage._sanitize_filename`` without importing boto/S3 stack."""
    name = name.replace("/", "_").replace("\\", "_")
    name = re.sub(r"\s+", "_", name.strip())
    name = "".join(ch for ch in name if unicodedata.category(ch)[0] != "C")
    return name[:200] or "file"


def _extract_contact_email(text: str) -> str:
    """Prefer first e-mail in « Thông tin liên hệ »; else whole string trimmed."""
    raw = (text or "").strip()
    if not raw:
        return ""
    m = _EMAIL_RE.search(raw)
    return m.group(0) if m else raw


def official_form_pdf_backup_zip_path(official_bieu_mau: Optional[Dict[str, Any]]) -> Optional[str]:
    """
    Relative path inside admin backup ZIP for the official merged PDF.

    Format: ``submitted/{Tên_sáng_kiến}_{tên_tác_giả}_{email_liên_hệ}.pdf`` (segments sanitized).
    Returns ``None`` when ``TRANG BÌA`` is missing so callers keep ``submitted/official-form.pdf``.
    """
    if not isinstance(official_bieu_mau, dict):
        return None
    bia = official_bieu_mau.get("TRANG BÌA")
    if not isinstance(bia, dict):
        return None
    ten = str(bia.get(_TRANG_BIA_TEN_SK) or "").strip()
    tac = str(bia.get(_TRANG_BIA_TAC_GIA) or "").strip()
    lien = str(bia.get(_TRANG_BIA_LIEN_HE) or "").strip()
    email = _extract_contact_email(lien)
    if not ten and not tac and not email:
        return None
    part_ten = _sanitize_filename(ten) if ten else "Ten_sang_kien"
    part_tac = _sanitize_filename(tac) if tac else "tac_gia"
    part_mail = _sanitize_filename(email) if email else "email_lien_he"
    stem = f"{part_ten}_{part_tac}_{part_mail}"
    if len(stem) > 180:
        stem = stem[:180]
    return f"submitted/{stem}.pdf"


def backup_zip_attachment_filename(
    *,
    owner_email: Optional[str],
    owner_full_name: Optional[str],
    public_application_id: str,
) -> str:
    """
    Safe Content-Disposition name: {username}_{applicationId}.zip
    Username prefers email local-part, else full name; falls back to ``applicant``.
    """
    user_seg = "applicant"
    email = (owner_email or "").strip()
    if email and "@" in email:
        local = email.split("@", 1)[0].strip()
        user_seg = _sanitize_filename(local) or "applicant"
    else:
        name = (owner_full_name or "").strip()
        if name:
            user_seg = _sanitize_filename(name) or "applicant"
    pid = (public_application_id or "").strip()
    base = f"{user_seg}_{pid}.zip"
    return _sanitize_filename(base) or base
