from __future__ import annotations

import logging
from typing import Any

from app.modules.takeoff.application.excel_exporter import (
    export_takeoff_to_excel as export_takeoff_to_excel_pkg,
)

logger = logging.getLogger(__name__)


class DrawingPipelineExportMixin:
    """Mixin for Excel export and full detail retrieval."""

    def export_takeoff_to_excel(self, takeoff_id: str) -> bytes:
        """Xuất toàn bộ bảng bóc tách dự toán BoQ (Phụ lục 03a) và Bảng giá thị trường 2026 ra file Excel (.xlsx) chuẩn doanh nghiệp."""
        takeoff = self._erp_client.get_drawing_takeoff(takeoff_id)
        if not takeoff:
            raise ValueError(f"Không tìm thấy hồ sơ bóc tách ID: {takeoff_id}")
        items = self._erp_client.list_drawing_takeoff_items(takeoff_id) or []
        return export_takeoff_to_excel_pkg(takeoff, items)

    def get_takeoff_full_detail(self, takeoff_id: str) -> dict[str, Any]:
        """Lấy toàn bộ thông tin chi tiết của một hồ sơ bóc tách bản vẽ kèm BoQ items."""
        takeoff = self._erp_client.get_drawing_takeoff(takeoff_id)
        if not takeoff:
            raise ValueError(f"Không tìm thấy hồ sơ bóc tách ID: {takeoff_id}")

        items = self._erp_client.list_drawing_takeoff_items(takeoff_id) or []

        metrics = {
            "total_estimated_cost_vnd": float(
                takeoff.get("total_estimated_cost_vnd") or 0
            ),
            "total_concrete_volume_m3": float(
                takeoff.get("total_concrete_volume_m3") or 0
            ),
            "total_rebar_weight_tons": float(
                takeoff.get("total_rebar_weight_tons") or 0
            ),
            "total_formwork_area_m2": float(takeoff.get("total_formwork_area_m2") or 0),
            "total_earthwork_volume_m3": float(
                takeoff.get("total_earthwork_volume_m3") or 0
            ),
        }

        return {
            "status": "success",
            "takeoff": takeoff,
            "items": items,
            "metrics": metrics,
        }
