from __future__ import annotations

"""Statutory Construction Cost Summary & Markup Calculation Engine.
Strictly complies with:
- Vietnam Construction Law 2025 (Law No. 135/2025/QH15 - effective July 1, 2026)
- Decree 206/2026/ND-CP (Management of Construction Investment Costs)
- Circular 38/2026/TT-BXD (System of Construction Cost Estimation Norms 2026)
- Circular 12/2021/TT-BXD & SXD Hai Phong Guidelines
"""

import logging
from typing import Any

logger = logging.getLogger("dscons.takeoff.statutory_cost")

STATUTORY_COEFFICIENTS: dict[str, dict[str, float]] = {
    "civil_building": {
        "project_type_name": "Công trình Dân dụng (Nhà văn hóa, Trụ sở)",
        "k_C": 7.3,  # 7.3% Chi phí chung
        "k_tam": 1.2,  # 1.2% Nhà tạm để ở và điều hành thi công
        "k_TT": 2.5,  # 2.5% Một số công tác không xác định từ thiết kế
        "k_TL": 5.5,  # 5.5% Thu nhập chịu thuế tính trước
        "k_VAT": 8.0,  # 8.0% Thuế GTGT
        "k_DP1": 5.0,  # 5.0% Dự phòng khối lượng phát sinh
        "k_DP2": 3.0,  # 3.0% Dự phòng trượt giá
    },
    "hydraulic_culvert": {
        "project_type_name": "Công trình Nông nghiệp & PTNT / Thủy lợi (Kè, Cống, Kênh mương)",
        "k_C": 5.5,  # 5.5% Chi phí chung
        "k_tam": 1.0,  # 1.0% Nhà tạm để ở và điều hành thi công
        "k_TT": 2.0,  # 2.0% Một số công tác không xác định từ thiết kế
        "k_TL": 5.5,  # 5.5% Thu nhập chịu thuế tính trước
        "k_VAT": 8.0,  # 8.0% Thuế GTGT
        "k_DP1": 5.0,  # 5.0% Dự phòng khối lượng phát sinh
        "k_DP2": 3.0,  # 3.0% Dự phòng trượt giá
    },
    "infrastructure_transport": {
        "project_type_name": "Công trình Giao thông / Hạ tầng kỹ thuật (Đường, Cầu)",
        "k_C": 6.2,  # 6.2% Chi phí chung
        "k_tam": 1.2,  # 1.2% Nhà tạm để ở và điều hành thi công
        "k_TT": 2.0,  # 2.0% Một số công tác không xác định từ thiết kế
        "k_TL": 5.5,  # 5.5% Thu nhập chịu thuế tính trước
        "k_VAT": 8.0,  # 8.0% Thuế GTGT
        "k_DP1": 5.0,  # 5.0% Dự phòng khối lượng phát sinh
        "k_DP2": 3.0,  # 3.0% Dự phòng trượt giá
    },
    "industrial": {
        "project_type_name": "Công trình Công nghiệp (Nhà xưởng, Kho bãi)",
        "k_C": 6.5,
        "k_tam": 1.2,
        "k_TT": 2.5,
        "k_TL": 5.5,
        "k_VAT": 8.0,
        "k_DP1": 5.0,
        "k_DP2": 3.0,
    },
}


class StatutoryCostSummaryEngine:
    """Calculates full statutory general cost summary according to Decree 206/2026/ND-CP."""

    @classmethod
    def get_coefficients(cls, drawing_type: str = "civil_building") -> dict[str, Any]:
        dt_key = str(drawing_type or "").lower()
        if (
            "culvert" in dt_key
            or "hydraulic" in dt_key
            or "ke" in dt_key
            or "kenh" in dt_key
            or "revetment" in dt_key
        ):
            return STATUTORY_COEFFICIENTS["hydraulic_culvert"]
        elif (
            "transport" in dt_key
            or "road" in dt_key
            or "bridge" in dt_key
            or "giao_thong" in dt_key
        ):
            return STATUTORY_COEFFICIENTS["infrastructure_transport"]
        elif "industrial" in dt_key or "factory" in dt_key:
            return STATUTORY_COEFFICIENTS["industrial"]
        return STATUTORY_COEFFICIENTS["civil_building"]

    @classmethod
    def calculate_statutory_summary(
        cls,
        items: list[dict[str, Any]],
        drawing_type: str = "civil_building",
        vat_rate: float | None = None,
        include_contingency: bool = True,
    ) -> dict[str, Any]:
        """Compute the full 9-row Statutory General Cost Summary Table (TH Kinh Phí Xây Dựng 2026)."""
        coeffs = cls.get_coefficients(drawing_type)
        actual_vat_rate = vat_rate if vat_rate is not None else coeffs["k_VAT"]

        # 1. Direct Cost T = VL + NC + M
        total_vl = 0.0
        total_nc = 0.0
        total_m = 0.0
        total_direct_t = 0.0

        for itm in items:
            qty = float(itm.get("quantity") or 0.0)
            u_price = float(itm.get("unit_price_vnd") or itm.get("unit_price") or 0.0)
            tot_item = float(
                itm.get("total_amount_vnd")
                or itm.get("total")
                or round(qty * u_price, 0)
            )

            # Decompose item rate
            vl_item = float(itm.get("material_cost_vnd") or 0.0)
            nc_item = float(itm.get("labor_cost_vnd") or 0.0)
            m_item = float(itm.get("equipment_cost_vnd") or 0.0)

            if vl_item + nc_item + m_item > 0:
                total_vl += vl_item * qty
                total_nc += nc_item * qty
                total_m += m_item * qty
            else:
                from .boq_rate_breakdown_service import BoqRateBreakdownEngine

                brk = BoqRateBreakdownEngine.breakdown_item_rate(
                    item_name=itm.get("item_name", ""),
                    category=itm.get("category", ""),
                    unit=itm.get("unit", "m3"),
                    total_unit_price=u_price,
                    norm_code=itm.get("norm_code", "AF.11110"),
                )
                vl_val = float(brk.get("material_cost_vnd") or 0.0)
                nc_val = float(brk.get("labor_cost_vnd") or 0.0)
                m_val = float(brk.get("equipment_cost_vnd") or 0.0)
                total_vl += vl_val * qty
                total_nc += nc_val * qty
                total_m += m_val * qty

            total_direct_t += tot_item

        total_direct_t = round(total_direct_t, 0)
        total_vl = round(total_vl, 0)
        total_nc = round(total_nc, 0)
        total_m = round(total_m, 0)

        # 2. Indirect Cost GT = C + T_tam + TT
        c_overhead = round(total_direct_t * (coeffs["k_C"] / 100.0), 0)
        t_tam_office = round(total_direct_t * (coeffs["k_tam"] / 100.0), 0)
        tt_unspecified = round(total_direct_t * (coeffs["k_TT"] / 100.0), 0)
        total_indirect_gt = c_overhead + t_tam_office + tt_unspecified

        # 3. Statutory Profit Margin TL = (T + GT) * k_TL
        total_t_plus_gt = total_direct_t + total_indirect_gt
        statutory_profit_tl = round(total_t_plus_gt * (coeffs["k_TL"] / 100.0), 0)

        # 4. Total Construction Cost Before Tax G = T + GT + TL
        cost_before_tax_g = total_direct_t + total_indirect_gt + statutory_profit_tl

        # 5. Value Added Tax (VAT) = G * k_VAT
        vat_amount = round(cost_before_tax_g * (actual_vat_rate / 100.0), 0)

        # 6. Total Construction Cost After Tax G_xd = G + VAT
        cost_after_tax_gxd = cost_before_tax_g + vat_amount

        # 7. Contingency G_dp = G_dp1 + G_dp2
        contingency_dp1 = (
            round(cost_after_tax_gxd * (coeffs["k_DP1"] / 100.0), 0)
            if include_contingency
            else 0.0
        )
        contingency_dp2 = (
            round(cost_after_tax_gxd * (coeffs["k_DP2"] / 100.0), 0)
            if include_contingency
            else 0.0
        )
        total_contingency_dp = contingency_dp1 + contingency_dp2

        # 8. Grand Total Budget Sigma_G_DT
        grand_total_budget = cost_after_tax_gxd + total_contingency_dp

        # Build structured table rows
        table_rows = [
            {
                "index": "I",
                "code": "T",
                "title": "CHI PHÍ TRỰC TIẾP",
                "calculation_formula": "VL + NC + M",
                "coefficient_str": "100.0%",
                "amount_vnd": total_direct_t,
                "is_header": True,
                "notes": "Tổng chi phí Vật liệu, Nhân công, Máy thi công từ bảng bóc tách BoQ",
            },
            {
                "index": "1.1",
                "code": "VL",
                "title": "Chi phí Vật liệu",
                "calculation_formula": "Theo đơn giá TBG Sở Xây Dựng Hải Phòng 2026",
                "coefficient_str": f"{(total_vl / total_direct_t * 100 if total_direct_t > 0 else 65):.1f}%",
                "amount_vnd": total_vl,
                "is_header": False,
                "notes": "Cát vàng 710k, Đá 1x2 320k, Xi măng, Thép CB400...",
            },
            {
                "index": "1.2",
                "code": "NC",
                "title": "Chi phí Nhân công",
                "calculation_formula": "Theo đơn giá nhân công XD Hải Phòng (Thợ bậc 3.5/7)",
                "coefficient_str": f"{(total_nc / total_direct_t * 100 if total_direct_t > 0 else 25):.1f}%",
                "amount_vnd": total_nc,
                "is_header": False,
                "notes": "325.000 đ/công thợ xây dựng",
            },
            {
                "index": "1.3",
                "code": "M",
                "title": "Chi phí Máy thi công",
                "calculation_formula": "Theo bảng giá ca máy & thiết bị thi công 2026",
                "coefficient_str": f"{(total_m / total_direct_t * 100 if total_direct_t > 0 else 10):.1f}%",
                "amount_vnd": total_m,
                "is_header": False,
                "notes": "Máy đào 0.8m3, Búa rung, Máy lu, Máy trộn bê tông",
            },
            {
                "index": "II",
                "code": "GT",
                "title": "CHI PHÍ GIÁN TIẾP",
                "calculation_formula": "C + T_tạm + TT",
                "coefficient_str": f"{coeffs['k_C'] + coeffs['k_tam'] + coeffs['k_TT']:.1f}% T",
                "amount_vnd": total_indirect_gt,
                "is_header": True,
                "notes": "Quy định tại Nghị định 206/2026/NĐ-CP & TT 38/2026/TT-BXD",
            },
            {
                "index": "2.1",
                "code": "C",
                "title": "Chi phí chung",
                "calculation_formula": f"T * {coeffs['k_C']}%",
                "coefficient_str": f"{coeffs['k_C']}%",
                "amount_vnd": c_overhead,
                "is_header": False,
                "notes": "Chi phí quản lý doanh nghiệp, ban điều hành công trường",
            },
            {
                "index": "2.2",
                "code": "T_tạm",
                "title": "Chi phí nhà tạm để ở và điều hành thi công",
                "calculation_formula": f"T * {coeffs['k_tam']}%",
                "coefficient_str": f"{coeffs['k_tam']}%",
                "amount_vnd": t_tam_office,
                "is_header": False,
                "notes": "Lán trại, nhà tạm chỉ huy, kho bãi tại hiện trường",
            },
            {
                "index": "2.3",
                "code": "TT",
                "title": "Chi phí một số công việc không xác định từ thiết kế",
                "calculation_formula": f"T * {coeffs['k_TT']}%",
                "coefficient_str": f"{coeffs['k_TT']}%",
                "amount_vnd": tt_unspecified,
                "is_header": False,
                "notes": "Di chuyển máy móc, an toàn lao động, thí nghiệm hiện trường",
            },
            {
                "index": "III",
                "code": "TL",
                "title": "THU NHẬP CHỊU THUẾ TÍNH TRƯỚC (LỢI NHUẬN)",
                "calculation_formula": f"(T + GT) * {coeffs['k_TL']}%",
                "coefficient_str": f"{coeffs['k_TL']}%",
                "amount_vnd": statutory_profit_tl,
                "is_header": True,
                "notes": "Lợi nhuận định mức theo quy định của Nhà nước",
            },
            {
                "index": "IV",
                "code": "G",
                "title": "CHI PHÍ XÂY DỰNG TRƯỚC THUẾ",
                "calculation_formula": "T + GT + TL",
                "coefficient_str": "-",
                "amount_vnd": cost_before_tax_g,
                "is_header": True,
                "notes": "Tổng chi phí trực tiếp, gián tiếp và lợi nhuận trước thuế",
            },
            {
                "index": "V",
                "code": "VAT",
                "title": "THUẾ GIÁ TRỊ GIA TĂNG",
                "calculation_formula": f"G * {actual_vat_rate}%",
                "coefficient_str": f"{actual_vat_rate}%",
                "amount_vnd": vat_amount,
                "is_header": True,
                "notes": "Thuế suất GTGT theo quy định tài chính hiện hành",
            },
            {
                "index": "VI",
                "code": "G_xd",
                "title": "CHI PHÍ XÂY DỰNG SAU THUẾ",
                "calculation_formula": "G + VAT",
                "coefficient_str": "-",
                "amount_vnd": cost_after_tax_gxd,
                "is_header": True,
                "notes": "Giá trị hợp đồng thi công xây dựng chính thức",
            },
            {
                "index": "VII",
                "code": "G_dp",
                "title": "CHI PHÍ DỰ PHÒNG",
                "calculation_formula": f"G_xd * {coeffs['k_DP1'] + coeffs['k_DP2']}%",
                "coefficient_str": f"{coeffs['k_DP1'] + coeffs['k_DP2']}%",
                "amount_vnd": total_contingency_dp,
                "is_header": True,
                "notes": f"Dự phòng phát sinh ({coeffs['k_DP1']}%) + Dự phòng trượt giá ({coeffs['k_DP2']}%)",
            },
            {
                "index": "VIII",
                "code": "TOTAL",
                "title": "TỔNG DỰ TOÁN GÓI THẦU (GRAND TOTAL)",
                "calculation_formula": "G_xd + G_dp",
                "coefficient_str": "-",
                "amount_vnd": grand_total_budget,
                "is_header": True,
                "is_grand_total": True,
                "notes": "Tổng mức đầu tư gói thầu xây dựng hoàn chỉnh",
            },
        ]

        return {
            "status": "success",
            "project_type": drawing_type,
            "project_type_name": coeffs["project_type_name"],
            "legal_basis": "Nghị định 206/2026/NĐ-CP & Thông tư 38/2026/TT-BXD",
            "vat_rate_pct": actual_vat_rate,
            "total_direct_t": total_direct_t,
            "total_indirect_gt": total_indirect_gt,
            "statutory_profit_tl": statutory_profit_tl,
            "cost_before_tax_g": cost_before_tax_g,
            "vat_amount": vat_amount,
            "cost_after_tax_gxd": cost_after_tax_gxd,
            "total_contingency_dp": total_contingency_dp,
            "grand_total_budget": grand_total_budget,
            "table_rows": table_rows,
        }
