from __future__ import annotations

"""Excel Export Engine for Drawing Takeoff & BoQ / 2026 Cost Estimation.
Generates a complete 4-sheet professional workbook:
1. TH_KinhPhi: Statutory Cost Summary according to Decree 206/2026/ND-CP (T, GT, TL, G, VAT, G_xd, G_dp, TOTAL)
2. BoQ_ChiTiet: Bill of Quantities with geometric dimension breakdown formulas
3. PhanRa_DonGia: Rate breakdown into Materials (VL), Labor (NC), Machinery (M)
4. TongHop_VatTu: Material Requisition Schedule with Hai Phong State Prices 2026
"""

import io
import logging
from typing import Any

import openpyxl

from .excel_sheet_boq import build_boq_sheet
from .excel_sheet_materials import build_materials_sheet
from .excel_sheet_rate_breakdown import build_rate_breakdown_sheet
from .excel_sheet_statutory import build_statutory_sheet

logger = logging.getLogger("dscons.takeoff.excel_exporter")


def export_takeoff_to_excel(
    takeoff: dict[str, Any],
    items: list[dict[str, Any]],
    output_path: str | None = None,
) -> bytes:
    """Generate professional 4-sheet Excel workbook from takeoff and items."""
    wb = openpyxl.Workbook()

    # Sheet 1: Statutory Cost Summary
    ws1 = wb.active
    build_statutory_sheet(ws1, takeoff, items)

    # Sheet 2: BoQ Detailed
    ws2 = wb.create_sheet(title="2. BoQ Khối Lượng")
    build_boq_sheet(ws2, takeoff, items)

    # Sheet 3: Rate Breakdown (VL + NC + M)
    ws3 = wb.create_sheet(title="3. Đơn Giá Chi Tiết")
    build_rate_breakdown_sheet(ws3, takeoff, items)

    # Sheet 4: Material Requisition
    ws4 = wb.create_sheet(title="4. Tổng Hợp Vật Tư")
    build_materials_sheet(ws4, takeoff, items)

    buffer = io.BytesIO()
    wb.save(buffer)
    excel_bytes = buffer.getvalue()

    if output_path:
        with open(output_path, "wb") as f:
            f.write(excel_bytes)
        logger.info(
            "[TAKEOFF] Đã xuất file Excel dự toán 4 sheet thành công: %s", output_path
        )

    return excel_bytes
