from __future__ import annotations

import logging
import re
from pathlib import Path
from typing import Any

logger = logging.getLogger(__name__)


class DrawingPdfHsmtItemsMixin:
    def extract_hsmt_items_from_pdf(
        self, hsmt_pdf_path: Path | str
    ) -> list[dict[str, Any]]:
        """Trích xuất tự động danh mục BoQ, khối lượng mời thầu từ tài liệu PDF e-GP / Dự toán với Đơn Giá Động (Dynamic Pricing)."""
        import pymupdf

        pdf_path = Path(hsmt_pdf_path)
        if not pdf_path.exists() or pdf_path.suffix.lower() != ".pdf":
            return []
        raw_items: list[dict[str, Any]] = []
        item_order = 1

        try:
            doc = pymupdf.open(str(pdf_path))
            for page in doc:
                tables = page.find_tables()
                for t in tables:
                    rows = t.extract()
                    for r in rows:
                        clean_r = [str(c or "").strip().replace("\n", " ") for c in r]
                        if not clean_r or len(clean_r) < 3:
                            continue
                        code, name = clean_r[0], clean_r[1]
                        if code in ["STT", "Mã hiệu", ""] or not name:
                            continue

                        qty_str = clean_r[2] if len(clean_r) > 2 else "0"
                        unit_str = clean_r[3] if len(clean_r) > 3 else ""

                        try:
                            qty_clean = qty_str.replace(".", "").replace(",", ".")
                            qty_val = float(qty_clean)
                        except Exception:
                            qty_val = 0.0

                        if qty_val <= 0 or not re.match(r"^[1-3]\.[0-9]+$", code):
                            continue

                        nl = name.lower()
                        cat = "earthwork"
                        if "bê tông" in nl or "bt lót" in nl:
                            cat = "concrete"
                        elif "cốt thép" in nl or "thép" in nl or "inox" in nl:
                            cat = "rebar"
                        elif "ván khuôn" in nl:
                            cat = "formwork"
                        elif (
                            "trát" in nl
                            or "láng" in nl
                            or "sơn" in nl
                            or "cửa" in nl
                            or "đan" in nl
                            or "gạch" in nl
                        ):
                            cat = "finishing"

                        raw_items.append(
                            {
                                "item_order": item_order,
                                "wbs_code": code,
                                "norm_code": f"TT.{code.replace('.', '')}",
                                "item_name": name,
                                "category": cat,
                                "dimension_formula": f"Theo Biểu mẫu mời thầu e-GP (Khối lượng: {qty_str} {unit_str})",
                                "unit": unit_str,
                                "quantity": qty_val,
                                "unit_price_vnd": 0,
                                "total_amount_vnd": 0,
                                "price_source_url": f"/dashboard/material-price-comparison?q={name[:25].replace(' ', '+')}",
                            }
                        )
                        item_order += 1
        except Exception as e:
            logger.error("[TAKEOFF] Lỗi bóc tách HSMT PDF '%s': %s", pdf_path.name, e)

        # Apply dual grounding: SXD State Published Prices 2026 + Learned Rules Enforcement
        if hasattr(self, "apply_learned_rules_and_state_prices"):
            return self.apply_learned_rules_and_state_prices(
                raw_items, drawing_type="hydraulic_culvert"
            )
        return raw_items
