from __future__ import annotations

import logging
from typing import Any

logger = logging.getLogger("dscons.invoice_truth.handlers")


class TruthSyncHandlersMixin:
    """Item-level insertion handlers for Truth synchronization."""

    def _sync_owned_equipment(
        self,
        cur: Any,
        company_id: str,
        inv_id: str,
        series: str,
        inv_num: str,
        seller: str,
        issue_dt: Any,
        project_id: str | None,
        item: dict[str, Any],
        classification: dict[str, Any],
        eq_code: str,
        stats: dict[str, Any],
    ) -> None:
        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,
            "bulldozer": 14.0,
            "roller": 10.0,
            "truck": 12.0,
            "crane": 18.0,
            "generator": 4.5,
            "concrete_cutter": 2.5,
            "compactor": 1.8,
            "compressor": 0.0,
            "drill": 0.0,
            "welder": 0.0,
            "steel_bender": 0.0,
            "other": 5.0,
        }
        eq_type = classification["equipment_type"]
        hourly_rate = rate_map.get(eq_type, 200000)
        fuel_norm = fuel_map.get(eq_type, 0.0)

        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,
                brand_model = EXCLUDED.brand_model,
                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();
        """,
            (
                company_id,
                str(eq_code)[:100],
                str(item["item_name"])[:255],
                str(eq_type)[:100],
                str(classification["brand_model"])[:150],
                hourly_rate,
                fuel_norm,
                project_id,
                f"Tài sản mua sắm thực tế theo HĐ {series}-{inv_num} ngày {issue_dt} từ {seller}. Đơn giá: {float(item['unit_price']):,.0f} VNĐ.",
                inv_id,
                f"{series}-{inv_num}"[:100],
                float(item["total_amount"]),
                str(seller)[:255],
            ),
        )
        stats["equipment_assets_added"] += 1
        stats["equipment_details"].append(
            {
                "code": eq_code,
                "name": item["item_name"],
                "type": classification["equipment_type"],
                "brand_model": classification["brand_model"],
                "purchase_cost_vnd": float(item["total_amount"]),
                "invoice": f"{series}-{inv_num}",
                "seller": seller,
            }
        )

    def _sync_warehouse_material(
        self,
        cur: Any,
        company_id: str,
        mat_code: str,
        item: dict[str, Any],
        mat_group: str,
        seller: str,
        seller_mst: str,
        inv_id: str,
        series: str,
        inv_num: str,
        issue_dt: Any,
        project_id: str | None,
        wbs_id: str | None,
        stats: dict[str, Any],
    ) -> None:
        cur.execute(
            """
            INSERT INTO erp_warehouse_inventory (
                company_id, item_code, item_name, material_group,
                unit, quantity_received, quantity_remaining,
                unit_price_vnd, total_value_vnd,
                supplier_name, supplier_tax_code,
                source_invoice_id, source_invoice_item_id,
                invoice_series_number, receipt_date,
                warehouse_location, status,
                allocated_project_id, allocated_wbs_id, notes,
                created_at, updated_at
            ) VALUES (
                %s, %s, %s, %s,
                %s, %s, %s,
                %s, %s,
                %s, %s,
                %s, %s,
                %s, %s,
                'KHO TỔNG CÔNG TY (HẢI PHÒNG)', 'CHỜ_XUẤT_CÔNG_TRƯỜNG',
                %s, %s, %s,
                NOW(), NOW()
            );
        """,
            (
                company_id,
                str(mat_code)[:100],
                str(item["item_name"])[:255],
                str(mat_group)[:100],
                str(item["unit"])[:50],
                float(item["quantity"]),
                float(item["quantity"]),
                float(item["unit_price"]),
                float(item["total_amount"]),
                str(seller)[:255],
                str(seller_mst)[:50],
                inv_id,
                item.get("id"),
                f"{series}-{inv_num}"[:100],
                issue_dt,
                project_id,
                wbs_id,
                f"Nhập kho từ HĐ số {series}-{inv_num} ngày {issue_dt} của {seller}.",
            ),
        )
        stats["warehouse_materials_staged"] += 1
        stats["material_summary"][mat_group] = (
            stats["material_summary"].get(mat_group, 0) + 1
        )
