from __future__ import annotations

import logging
from typing import Any

logger = logging.getLogger(__name__)


class ErpTakeoffRulesApplyMixin:
    def apply_chat_suggested_corrections(
        self,
        takeoff_id: str,
        suggested_items: list[dict[str, Any]],
        message_id: str | None = None,
    ) -> dict[str, Any]:
        """Áp dụng danh sách các dòng BoQ hiệu chỉnh từ hội thoại huấn luyện vào bảng bóc tách chính."""
        from uuid import uuid4

        with self.get_connection() as conn:
            with conn.cursor() as cur:
                # If replacement mode: delete old items and re-insert updated ones
                cur.execute(
                    "DELETE FROM erp_drawing_takeoff_items WHERE takeoff_id = %s;",
                    (takeoff_id,),
                )

                inserted_items = []
                for idx, itm in enumerate(suggested_items):
                    item_id = str(uuid4())
                    wbs_code = itm.get("wbs_code") or f"1.{idx + 1}"
                    norm_code = itm.get("norm_code") or "AF.11110"
                    item_name = itm.get("item_name") or f"Hạng mục {idx + 1}"
                    category = itm.get("category") or "concrete"
                    dim_formula = itm.get("dimension_formula") or ""
                    unit = itm.get("unit") or "m3"
                    qty = float(itm.get("quantity") or 0)
                    price = float(itm.get("unit_price_vnd") or 0)
                    total_amount = float(itm.get("total_amount_vnd") or (qty * price))

                    cur.execute(
                        """
                        INSERT INTO erp_drawing_takeoff_items (
                            id, takeoff_id, item_order, wbs_code, norm_code,
                            item_name, category, dimension_formula, unit,
                            quantity, unit_price_vnd, total_amount_vnd, created_at
                        ) VALUES (
                            %s, %s, %s, %s, %s,
                            %s, %s, %s, %s,
                            %s, %s, %s, NOW()
                        ) RETURNING *;
                    """,
                        (
                            item_id,
                            takeoff_id,
                            idx + 1,
                            wbs_code,
                            norm_code,
                            item_name,
                            category,
                            dim_formula,
                            unit,
                            qty,
                            price,
                            total_amount,
                        ),
                    )
                    inserted_items.append(cur.fetchone())

                # Recompute takeoff header totals
                tot_cost = sum(
                    float(i.get("total_amount_vnd") or 0) for i in inserted_items
                )
                tot_concrete = sum(
                    float(i.get("quantity") or 0)
                    for i in inserted_items
                    if i.get("category") == "concrete"
                )
                tot_rebar = sum(
                    float(i.get("quantity") or 0)
                    for i in inserted_items
                    if i.get("category") == "rebar"
                )
                tot_formwork = sum(
                    float(i.get("quantity") or 0)
                    for i in inserted_items
                    if i.get("category") == "formwork"
                )
                tot_earthwork = sum(
                    float(i.get("quantity") or 0)
                    for i in inserted_items
                    if i.get("category") == "earthwork"
                )

                cur.execute(
                    """
                    UPDATE erp_drawing_takeoffs
                    SET total_estimated_cost_vnd = %s,
                        total_concrete_volume_m3 = %s,
                        total_rebar_weight_tons = %s,
                        total_formwork_area_m2 = %s,
                        total_earthwork_volume_m3 = %s,
                        confidence_score = 99,
                        confidence_level = 'human_verified',
                        ai_analysis_notes = 'Đã cập nhật và áp dụng toàn bộ hiệu chỉnh theo phản hồi của Kỹ Sư Trưởng QS.',
                        updated_at = NOW()
                    WHERE id = %s;
                """,
                    (
                        tot_cost,
                        tot_concrete,
                        tot_rebar,
                        tot_formwork,
                        tot_earthwork,
                        takeoff_id,
                    ),
                )

                if message_id:
                    cur.execute(
                        "UPDATE erp_ai_takeoff_chat_messages SET applied = TRUE WHERE id = %s;",
                        (message_id,),
                    )

                conn.commit()

        return {
            "status": "success",
            "message": f"Đã áp dụng thành công {len(inserted_items)} đầu mục BoQ hiệu chỉnh vào bảng bóc tách!",
            "takeoff_id": takeoff_id,
            "items_count": len(inserted_items),
        }
