from __future__ import annotations

"""Equipment cost synchronizer and fuel logger."""


import logging
from typing import Any

logger = logging.getLogger(__name__)


class InvoiceAnalyticsEquipmentMixin:
    """Mixin for syncing invoices to machinery and equipment logs."""

    def sync_invoice_to_equipment(self, invoice_id: str) -> dict[str, Any]:
        """Đồng bộ các mặt hàng máy móc / thiết bị trong hóa đơn sang phân hệ quản lý ca máy erp_equipment."""
        from app.modules.invoices.application.invoice_truth_extraction_service import (
            InvoiceTruthExtractionService,
        )

        truth_service = InvoiceTruthExtractionService()

        detail = self.get_invoice_detail(invoice_id)
        if not detail:
            raise ValueError("Không tìm thấy hóa đơn cần đồng bộ.")

        items = detail.get("items", [])
        seller = detail.get("seller_name", "")
        series = detail.get("invoice_series", "")
        inv_num = detail.get("invoice_number", "")
        issue_date = detail.get("issue_date", "")
        proj_id = detail.get("matched_project_id")

        synced_count = 0
        equipment_created = []

        with self.get_connection() as conn:
            with conn.cursor() as cur:
                cur.execute("SELECT id FROM companies LIMIT 1")
                c_row = cur.fetchone()
                comp_id = str(c_row["id"]) if c_row else None

                items_to_check = (
                    items
                    if items
                    else [
                        {
                            "item_name": detail.get("notes")
                            or f"Hàng hóa thiết bị từ {seller}",
                            "unit": "Chiếc",
                            "quantity": 1,
                            "unit_price_vnd": detail.get("subtotal_amount_vnd", 0),
                            "total_item_amount_vnd": detail.get("total_amount_vnd", 0),
                        }
                    ]
                )

                for idx, it in enumerate(items_to_check, 1):
                    it_name = it.get("item_name", "")
                    classification = truth_service.classify_item(
                        item_name=it_name,
                        unit=it.get("unit", "Chiếc"),
                        quantity=it.get("quantity", 1),
                        unit_price=it.get("unit_price_vnd", 0),
                        total_amount=it.get("total_item_amount_vnd", 0),
                        seller_name=seller,
                    )

                    if classification["classification"] in (
                        "OWNED_EQUIPMENT",
                        "POWER_TOOL",
                    ) or any(
                        k in it_name.lower()
                        for k in [
                            "máy",
                            "xe",
                            "thaco",
                            "volvo",
                            "komatsu",
                            "howo",
                            "hàn",
                            "khoan",
                            "cắt",
                            "đầm",
                            "nén khí",
                            "phát điện",
                        ]
                    ):
                        eq_type = classification.get("equipment_type") or "other"
                        prefix = (
                            "EQ-TOOL"
                            if eq_type
                            in (
                                "concrete_cutter",
                                "steel_bender",
                                "welder",
                                "drill",
                                "compactor",
                                "compressor",
                                "generator",
                            )
                            else "EQ-TRUTH"
                        )

                        cur.execute(
                            "SELECT count(*) as cnt FROM erp_equipment WHERE equipment_type = %s",
                            (eq_type,),
                        )
                        cnt = cur.fetchone()["cnt"] + 1
                        eq_code = f"{prefix}-{eq_type.upper()[:3]}-{cnt:03d}"

                        rate_map = {
                            "excavator": 480000,
                            "bulldozer": 380000,
                            "roller": 320000,
                            "truck": 420000,
                            "crane": 600000,
                            "generator": 250000,
                            "mixer": 150000,
                            "pump": 350000,
                            "concrete_cutter": 180000,
                            "steel_bender": 160000,
                            "welder": 140000,
                            "drill": 200000,
                            "compactor": 180000,
                            "compressor": 150000,
                            "other": 200000,
                        }
                        fuel_map = {
                            "excavator": 16.5,
                            "truck": 12.0,
                            "concrete_cutter": 2.5,
                            "compactor": 1.8,
                            "generator": 4.5,
                        }

                        cur.execute(
                            """
                            INSERT INTO erp_equipment (
                                company_id, equipment_code, equipment_name, equipment_type,
                                brand_model, ownership_type, hourly_rate_standard, fuel_norm_per_hour,
                                current_project_id, status, notes,
                                purchase_invoice_id, purchase_invoice_series_number,
                                purchase_cost_vnd, supplier_name, created_at, updated_at
                            ) VALUES (
                                %s, %s, %s, %s,
                                %s, 'owned', %s, %s,
                                %s, 'available', %s,
                                %s, %s,
                                %s, %s, NOW(), NOW()
                            )
                            ON CONFLICT (equipment_code) DO UPDATE
                            SET equipment_name = EXCLUDED.equipment_name,
                                purchase_cost_vnd = EXCLUDED.purchase_cost_vnd,
                                purchase_invoice_id = EXCLUDED.purchase_invoice_id,
                                purchase_invoice_series_number = EXCLUDED.purchase_invoice_series_number,
                                supplier_name = EXCLUDED.supplier_name,
                                updated_at = NOW();
                        """,
                            (
                                comp_id,
                                eq_code,
                                it_name,
                                eq_type,
                                classification.get("brand_model", it_name[:50]),
                                rate_map.get(eq_type, 200000),
                                fuel_map.get(eq_type, 0.0),
                                proj_id,
                                f"Đồng bộ từ HĐ {series}-{inv_num} ngày {issue_date} từ {seller}.",
                                invoice_id,
                                f"{series}-{inv_num}",
                                float(
                                    it.get("total_item_amount_vnd")
                                    or detail.get("total_amount_vnd", 0)
                                ),
                                seller,
                            ),
                        )
                        synced_count += 1
                        equipment_created.append(
                            {"code": eq_code, "name": it_name, "type": eq_type}
                        )

                conn.commit()

        return {
            "status": "success",
            "message": f"Đã đồng bộ {synced_count} máy móc/thiết bị từ hóa đơn {series}-{inv_num} sang phân hệ Ca Máy & Thiết Bị ERP.",
            "synced_count": synced_count,
            "equipment": equipment_created,
        }
