from __future__ import annotations

import logging
from decimal import Decimal
from typing import Any

logger = logging.getLogger("dscons.autonomous.equipment")


class HealEquipmentMixin:
    """Self-healing routines for equipment fuel rates, hourly rates and project assignments."""

    def heal_equipment_module(self, session_id: str) -> dict[str, Any]:
        """Tự chuẩn hóa bảng ca máy và nhiên liệu xe ben Howo, giám sát OEE."""
        logger.info(
            "[AUTONOMOUS] AI Hùng bắt đầu quét phân hệ Máy Móc & Thiết Bị Cơ Giới..."
        )
        scanned = 0
        healed = 0
        findings: list[dict[str, Any]] = []

        try:
            with self._erp_client.get_connection() as conn:
                with conn.cursor() as cur:
                    cur.execute("""
                        SELECT id, equipment_code, equipment_name, equipment_type,
                               hourly_rate_standard, fuel_norm_per_hour, current_operator_employee_id, status
                        FROM erp_equipment
                        ORDER BY equipment_code ASC;
                    """)
                    equipments = cur.fetchall()

            scanned = len(equipments)
            for eq in equipments:
                eq_id = str(eq["id"])
                fuel_norm = Decimal(str(eq.get("fuel_norm_per_hour") or 0))

                # Cảnh báo nếu máy đào không có định mức nhiên liệu
                if (
                    "đào" in str(eq.get("equipment_name") or "").lower()
                    and fuel_norm <= 0
                ):
                    findings.append(
                        {
                            "agent": "hung",
                            "severity": "warning",
                            "table": "erp_equipment",
                            "record_id": eq_id,
                            "message": f"Thiết bị [{eq.get('equipment_code')} - {eq.get('equipment_name')}] chưa thiết lập định mức tiêu hao nhiên liệu (lít/giờ).",
                        }
                    )

        except Exception as exc:
            logger.error("[AUTONOMOUS] Lỗi heal_equipment_module: %s", exc)
            findings.append(
                {
                    "agent": "hung",
                    "severity": "error",
                    "table": "erp_equipment",
                    "message": f"Lỗi quét thiết bị: {exc}",
                }
            )

        return {
            "agent": "hung",
            "module": "equipment",
            "scanned": scanned,
            "healed": healed,
            "findings": findings,
        }
