from __future__ import annotations

import logging
from datetime import datetime
from typing import Any

logger = logging.getLogger("dscons.missing_document.helpers")


class MissingDocumentHelpersMixin:
    """Formatting, normalization, and scaffolding helpers for missing document generation."""

    def _normalize_document_types(self, missing_document_types: list[str]) -> list[str]:
        """Chuẩn hóa danh sách đầu vào, loại bỏ rỗng và trùng lặp nhưng giữ thứ tự."""
        normalized: list[str] = []
        seen: set[str] = set()
        for item in missing_document_types:
            document_type = str(item or "").strip()
            if not document_type or document_type in seen:
                continue
            seen.add(document_type)
            normalized.append(document_type)
        return normalized

    def _get_document_scaffold(
        self,
        document_type: str,
        document_meta: dict[str, Any],
    ) -> dict[str, Any]:
        """Lấy scaffold theo tài liệu, fallback về khung markdown chung."""
        default_suffix = document_type.replace("_", "-")
        scaffold = _DOCUMENT_SCAFFOLDS.get(document_type)
        if scaffold:
            return scaffold

        return {
            "file_extension": "md",
            "generator_type": "markdown_outline",
            "template_key": None,
            "sections": [
                "Thông tin chung",
                "Căn cứ lập hồ sơ",
                "Nội dung chính",
                "Tài liệu đính kèm",
                "Xác nhận",
            ],
            "required_inputs": [
                "project_name",
                "document_number",
                "issue_date_text",
                "issuer_name",
            ],
            "output_filename_suffix": default_suffix,
            "notes": (
                f"Chưa có template chuyên biệt cho {document_meta.get('label') or document_type}, "
                "đang dùng khung chung an toàn."
            ),
        }

    def _build_output_filename(
        self,
        project_code: str,
        document_type: str,
        output_filename_suffix: str,
        file_extension: str,
    ) -> str:
        """Sinh tên file có thể ghi ra đĩa ở bước sau."""
        safe_project_code = project_code.strip().replace("/", "-").replace(" ", "-")
        return f"{safe_project_code}__{output_filename_suffix}.{file_extension}"

    def _humanize_document_type(self, document_type: str) -> str:
        """Chuyển document_type kỹ thuật thành nhãn dễ đọc khi chưa có label."""
        return document_type.replace("_", " ").strip().title()

    def _humanize_field_name(self, field_name: str) -> str:
        """Chuyển field kỹ thuật thành nhãn gần gũi hơn."""
        return field_name.replace(".", " / ").replace("_", " ").strip().capitalize()

    def _slugify(self, value: str) -> str:
        """Chuẩn hóa heading về slug ASCII đơn giản cho placeholder key."""
        normalized = value.strip().lower()
        replacements = {
            "ă": "a",
            "â": "a",
            "đ": "d",
            "ê": "e",
            "ô": "o",
            "ơ": "o",
            "ư": "u",
            "á": "a",
            "à": "a",
            "ả": "a",
            "ã": "a",
            "ạ": "a",
            "é": "e",
            "è": "e",
            "ẻ": "e",
            "ẽ": "e",
            "ẹ": "e",
            "í": "i",
            "ì": "i",
            "ỉ": "i",
            "ĩ": "i",
            "ị": "i",
            "ó": "o",
            "ò": "o",
            "ỏ": "o",
            "õ": "o",
            "ọ": "o",
            "ú": "u",
            "ù": "u",
            "ủ": "u",
            "ũ": "u",
            "ụ": "u",
            "ý": "y",
            "ỳ": "y",
            "ỷ": "y",
            "ỹ": "y",
            "ỵ": "y",
        }
        for source, target in replacements.items():
            normalized = normalized.replace(source, target)
        normalized = normalized.replace("/", " ").replace("-", " ")
        return "-".join(part for part in normalized.split() if part)

    def _utc_now(self) -> str:
        """Trả chuỗi thời gian UTC ISO cho metadata."""
        return datetime.now(UTC).isoformat()
