from __future__ import annotations

import json
import logging
from typing import Any

logger = logging.getLogger(__name__)


class ErpEquipmentMixin:
    def list_equipment(
        self, project_id: str | None = None, status: str | None = None
    ) -> list[dict[str, Any]]:
        """Lấy danh sách máy móc thiết bị, lọc theo dự án hoặc trạng thái."""
        sql = """
            SELECT e.*, p.project_name as current_project_name, emp.full_name as current_operator_name
            FROM erp_equipment e
            LEFT JOIN projects p ON e.current_project_id = p.id
            LEFT JOIN employees emp ON e.current_operator_employee_id = emp.id
            WHERE 1=1
        """
        params: list[Any] = []
        if project_id:
            sql += " AND e.current_project_id = %s"
            params.append(project_id)
        if status:
            sql += " AND e.status = %s"
            params.append(status)
        sql += " ORDER BY e.equipment_code ASC;"

        with self.get_connection() as conn, conn.cursor() as cur:
            cur.execute(sql, params)
            return cur.fetchall()

    def create_equipment(self, payload: dict[str, Any]) -> dict[str, Any]:
        """Thêm máy móc thiết bị mới vào hệ thống."""
        sql = """
            INSERT INTO erp_equipment (
                company_id, equipment_code, equipment_name, equipment_type,
                license_plate, brand_model, manufacture_year, ownership_type,
                hourly_rate_standard, fuel_norm_per_hour, current_project_id,
                current_operator_employee_id, status, notes
            ) VALUES (
                %(company_id)s, %(equipment_code)s, %(equipment_name)s, %(equipment_type)s,
                %(license_plate)s, %(brand_model)s, %(manufacture_year)s, %(ownership_type)s,
                %(hourly_rate_standard)s, %(fuel_norm_per_hour)s, %(current_project_id)s,
                %(current_operator_employee_id)s, %(status)s, %(notes)s
            ) RETURNING *;
        """
        with self.get_connection() as conn, conn.cursor() as cur:
            cur.execute(sql, payload)
            conn.commit()
            return cur.fetchone()

    def add_equipment_log(self, payload: dict[str, Any]) -> dict[str, Any]:
        """Ghi nhận nhật ký ca máy & tiêu hao nhiên liệu."""
        sql = """
            INSERT INTO erp_equipment_logs (
                equipment_id, project_id, operator_employee_id, log_date,
                shift_code, hours_operated, fuel_consumed_liters, work_description,
                meter_start, meter_end, ai_audit_flags
            ) VALUES (
                %(equipment_id)s, %(project_id)s, %(operator_employee_id)s, %(log_date)s,
                %(shift_code)s, %(hours_operated)s, %(fuel_consumed_liters)s, %(work_description)s,
                %(meter_start)s, %(meter_end)s, %(ai_audit_flags)s
            ) RETURNING *;
        """
        params = {
            **payload,
            "ai_audit_flags": json.dumps(payload.get("ai_audit_flags", [])),
        }
        with self.get_connection() as conn, conn.cursor() as cur:
            cur.execute(sql, params)
            conn.commit()
            return cur.fetchone()
