"""Enterprise AEC Document Taxonomy & Classification Hierarchy.

Defines the 2-Tier Hierarchical Classification for DSCons Construction ERP:
- 5 Mega-Groups (Nhóm nghiệp vụ)
- Sub-types (Loại văn bản cụ thể) with standard codes for automatic numbering {Số}/{Năm}/{Mã}-ĐS
"""

from __future__ import annotations

from typing import Any

# 1. Mega-Groups (Đại nhóm hồ sơ công trình)
DOCUMENT_GROUPS: dict[str, dict[str, str]] = {
    "legal": {
        "key": "legal",
        "name": "Pháp Lý & Hành Chính",
        "icon": "⚖️",
        "description": "Công văn, quyết định, thông báo, tờ trình, thư từ pháp lý",
    },
    "contract": {
        "key": "contract",
        "name": "Hợp Đồng & Đấu Thầu",
        "icon": "🤝",
        "description": "Hợp đồng xây dựng, phụ lục, báo giá, chào thầu, hồ sơ dự thầu",
    },
    "technical": {
        "key": "technical",
        "name": "Kỹ Thuật & Bản Vẽ",
        "icon": "📐",
        "description": "Thuyết minh dự toán sơ bộ, bản vẽ kỹ thuật, BPTC, chỉ dẫn kỹ thuật",
    },
    "site": {
        "key": "site",
        "name": "Hiện Trường & QA/QC",
        "icon": "🏗️",
        "description": "Biên bản hiện trường, nghiệm thu, nhật ký công trình, phiếu thí nghiệm",
    },
    "financial": {
        "key": "financial",
        "name": "Tài Chính & Ngân Hàng",
        "icon": "🏦",
        "description": "Ủy nhiệm chi (UNC), sao kê ngân hàng, giấy báo nợ/có, hóa đơn, IPC",
    },
    "other": {
        "key": "other",
        "name": "Khác & Tùy Biến",
        "icon": "✨",
        "description": "Các dạng tài liệu nghiệp vụ đặc thù do người dùng tự định nghĩa",
    },
}

# 2. Sub-Types (Danh mục phân loại chi tiết)
DOCUMENT_TYPES: list[dict[str, Any]] = [
    # --- 1. Pháp Lý & Hành Chính ---
    {
        "code": "CV",
        "name": "Công văn",
        "group": "legal",
        "full_label": "Công văn (CV)",
        "badge_color": "#60a5fa",
        "default_direction": "both",
    },
    {
        "code": "QĐ",
        "name": "Quyết định",
        "group": "legal",
        "full_label": "Quyết định (QĐ)",
        "badge_color": "#38bdf8",
        "default_direction": "incoming",
    },
    {
        "code": "TB",
        "name": "Thông báo",
        "group": "legal",
        "full_label": "Thông báo (TB)",
        "badge_color": "#22d3ee",
        "default_direction": "incoming",
    },
    {
        "code": "TTr",
        "name": "Tờ trình",
        "group": "legal",
        "full_label": "Tờ trình (TTr)",
        "badge_color": "#818cf8",
        "default_direction": "internal",
    },
    {
        "code": "THU",
        "name": "Thư từ / Thư mời",
        "group": "legal",
        "full_label": "Thư từ / Thư mời (THƯ)",
        "badge_color": "#a78bfa",
        "default_direction": "both",
    },
    {
        "code": "GUQ",
        "name": "Giấy giới thiệu / Giấy ủy quyền",
        "group": "legal",
        "full_label": "Giấy giới thiệu / Ủy quyền (GUQ)",
        "badge_color": "#c084fc",
        "default_direction": "outgoing",
    },
    # --- 2. Hợp Đồng & Đấu Thầu ---
    {
        "code": "HĐ",
        "name": "Hợp đồng kinh tế / Xây dựng",
        "group": "contract",
        "full_label": "Hợp đồng (HĐ)",
        "badge_color": "#34d399",
        "default_direction": "both",
    },
    {
        "code": "PLHĐ",
        "name": "Phụ lục hợp đồng",
        "group": "contract",
        "full_label": "Phụ lục hợp đồng (PLHĐ)",
        "badge_color": "#10b981",
        "default_direction": "both",
    },
    {
        "code": "BG",
        "name": "Báo giá / Đơn chào giá",
        "group": "contract",
        "full_label": "Báo giá / Chào giá (BG)",
        "badge_color": "#4ade80",
        "default_direction": "both",
    },
    {
        "code": "HSMT",
        "name": "Hồ sơ mời thầu / E-HSMT",
        "group": "contract",
        "full_label": "Hồ sơ mời thầu (HSMT)",
        "badge_color": "#a3e635",
        "default_direction": "incoming",
    },
    {
        "code": "HSDT",
        "name": "Hồ sơ dự thầu / Đơn dự thầu",
        "group": "contract",
        "full_label": "Hồ sơ dự thầu (HSDT)",
        "badge_color": "#facc15",
        "default_direction": "outgoing",
    },
    # --- 3. Kỹ Thuật & Bản Vẽ ---
    {
        "code": "TM",
        "name": "Thuyết minh & Dự toán sơ bộ",
        "group": "technical",
        "full_label": "Thuyết minh & Dự toán (TM)",
        "badge_color": "#f59e0b",
        "default_direction": "both",
    },
    {
        "code": "BV",
        "name": "Bản vẽ kỹ thuật / Thiết kế thi công",
        "group": "technical",
        "full_label": "Bản vẽ kỹ thuật (BV)",
        "badge_color": "#fb923c",
        "default_direction": "both",
    },
    {
        "code": "BPTC",
        "name": "Biện pháp tổ chức thi công",
        "group": "technical",
        "full_label": "Biện pháp thi công (BPTC)",
        "badge_color": "#f97316",
        "default_direction": "both",
    },
    {
        "code": "CDKT",
        "name": "Chỉ dẫn kỹ thuật / Tiêu chuẩn",
        "group": "technical",
        "full_label": "Chỉ dẫn kỹ thuật (CĐKT)",
        "badge_color": "#ea580c",
        "default_direction": "incoming",
    },
    # --- 4. Hiện Trường & QA/QC ---
    {
        "code": "BB",
        "name": "Biên bản hiện trường / Bàn giao",
        "group": "site",
        "full_label": "Biên bản hiện trường (BB)",
        "badge_color": "#94a3b8",
        "default_direction": "both",
    },
    {
        "code": "BBNT",
        "name": "Biên bản nghiệm thu QA/QC",
        "group": "site",
        "full_label": "Biên bản nghiệm thu (BBNT)",
        "badge_color": "#38bdf8",
        "default_direction": "both",
    },
    {
        "code": "NK",
        "name": "Nhật ký thi công công trình",
        "group": "site",
        "full_label": "Nhật ký thi công (NK)",
        "badge_color": "#818cf8",
        "default_direction": "internal",
    },
    {
        "code": "TN",
        "name": "Phiếu kết quả thí nghiệm / Kiểm định",
        "group": "site",
        "full_label": "Phiếu thí nghiệm (TN)",
        "badge_color": "#a855f7",
        "default_direction": "incoming",
    },
    {
        "code": "KCS",
        "name": "Biên bản kiểm tra vật tư nhập bãi",
        "group": "site",
        "full_label": "Kiểm tra vật tư (KCS)",
        "badge_color": "#ec4899",
        "default_direction": "both",
    },
    # --- 5. Tài Chính & Ngân Hàng ---
    {
        "code": "UNC",
        "name": "Ủy nhiệm chi / Lệnh chuyển tiền",
        "group": "financial",
        "full_label": "Ủy nhiệm chi (UNC)",
        "badge_color": "#10b981",
        "default_direction": "both",
    },
    {
        "code": "SK",
        "name": "Sao kê tài khoản ngân hàng",
        "group": "financial",
        "full_label": "Sao kê ngân hàng (SK)",
        "badge_color": "#14b8a6",
        "default_direction": "incoming",
    },
    {
        "code": "GBN",
        "name": "Giấy báo Nợ / Giấy báo Có",
        "group": "financial",
        "full_label": "Giấy báo Nợ / Có (GBN)",
        "badge_color": "#06b6d4",
        "default_direction": "incoming",
    },
    {
        "code": "HDDT",
        "name": "Hóa đơn điện tử GTGT",
        "group": "financial",
        "full_label": "Hóa đơn GTGT (HĐĐT)",
        "badge_color": "#3b82f6",
        "default_direction": "both",
    },
    {
        "code": "IPC",
        "name": "Chứng chỉ thanh toán đợt (IPC)",
        "group": "financial",
        "full_label": "Thanh toán đợt (IPC)",
        "badge_color": "#6366f1",
        "default_direction": "both",
    },
    {
        "code": "QT",
        "name": "Hồ sơ quyết toán / Thanh lý hợp đồng",
        "group": "financial",
        "full_label": "Quyết toán & Thanh lý (QT)",
        "badge_color": "#8b5cf6",
        "default_direction": "both",
    },
    # --- 6. Mở Rộng ---
    {
        "code": "KHAC",
        "name": "Loại văn bản khác (Tùy biến)",
        "group": "other",
        "full_label": "✨ Khác (Tự nhập mã)",
        "badge_color": "#64748b",
        "default_direction": "both",
    },
]

# Quick lookup mappings
DOCUMENT_TYPE_MAP: dict[str, dict[str, Any]] = {
    item["code"].upper(): item for item in DOCUMENT_TYPES
}


def get_document_type(code: str) -> dict[str, Any] | None:
    """Retrieve document type definition by code (case-insensitive)."""
    if not code:
        return None
    return DOCUMENT_TYPE_MAP.get(code.upper().strip())


def get_group_for_type(code: str) -> str:
    """Resolve document group key from document type code."""
    t = get_document_type(code)
    if t:
        return t["group"]
    # Heuristic fallback
    c = code.upper().strip()
    if c in ("CV", "QD", "QĐ", "TB", "TTR", "THU", "THƯ", "GUQ"):
        return "legal"
    if c in ("HD", "HĐ", "PLHD", "PLHĐ", "BG", "HSMT", "HSDT"):
        return "contract"
    if c in ("TM", "BV", "BPTC", "CDKT", "CĐKT", "DT"):
        return "technical"
    if c in ("BB", "BBNT", "NK", "TN", "KCS"):
        return "site"
    if c in ("UNC", "SK", "GBN", "HDDT", "HĐĐT", "IPC", "QT"):
        return "financial"
    return "other"


def get_taxonomy_grouped() -> dict[str, dict[str, Any]]:
    """Returns the full taxonomy grouped by Mega-Group with items."""
    grouped: dict[str, dict[str, Any]] = {}
    for g_key, g_info in DOCUMENT_GROUPS.items():
        grouped[g_key] = {
            **g_info,
            "items": [],
        }

    for item in DOCUMENT_TYPES:
        g = item["group"]
        if g in grouped:
            grouped[g]["items"].append(item)
        else:
            grouped["other"]["items"].append(item)

    return grouped
