from __future__ import annotations

import logging
from decimal import Decimal
from typing import Any

logger = logging.getLogger("dscons.autonomous.invoices")


class HealInvoicesMixin:
    """Self-healing routines for unlinked or pending tax invoices."""

    def heal_invoices_module(self, session_id: str) -> dict[str, Any]:
        """Tự động phân loại hóa đơn (Pillar 1-4) dựa trên danh sách suppliers chuẩn, tính toán bù trừ."""
        logger.info(
            "[AUTONOMOUS] AI Nam bắt đầu quét phân hệ Hóa Đơn & Dòng Tiền EVM..."
        )
        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, invoice_number, invoice_series, seller_tax_code, seller_name,
                               buyer_tax_code, subtotal_amount_vnd, vat_amount_vnd, total_amount_vnd,
                               reconciliation_status, matched_project_id, notes, created_at
                        FROM erp_invoices
                        ORDER BY created_at DESC
                        LIMIT 100;
                    """)
                    invoices = cur.fetchall()

            scanned = len(invoices)
            for inv in invoices:
                inv_id = str(inv["id"])
                seller_tax = str(inv.get("seller_tax_code") or "").strip()

                # Xác định Trụ cột kinh doanh chuẩn theo 4 Trụ Cột Định Sơn
                target_pillar = None
                if (
                    seller_tax == "0200149705"
                    or "thoát nước" in str(inv.get("seller_name") or "").lower()
                ):
                    target_pillar = "Trụ cột 2: Vận tải Xe ben Logistics"
                elif (
                    seller_tax == "0201889988"
                    or "loan khải" in str(inv.get("seller_name") or "").lower()
                ):
                    target_pillar = "Trụ cột 3: Cho thuê Ca máy Đào"
                elif (
                    seller_tax == "0201805660"
                    or "trung kiên" in str(inv.get("seller_name") or "").lower()
                ):
                    target_pillar = "Trụ cột 4: Vật tư & San lấp"
                else:
                    target_pillar = "Trụ cột 1: Thi công Xây lắp & Thủy lợi"

                current_notes = str(inv.get("notes") or "")
                needs_update = False
                update_fields: dict[str, Any] = {}
                reasons: list[str] = []

                if target_pillar and target_pillar not in current_notes:
                    new_notes = f"[{target_pillar}] {current_notes}".strip()
                    update_fields["notes"] = new_notes
                    reasons.append(f"Gán nhãn {target_pillar}")
                    needs_update = True

                # Kiểm tra số học VAT
                pretax = Decimal(str(inv.get("subtotal_amount_vnd") or 0))
                vat = Decimal(str(inv.get("vat_amount_vnd") or 0))
                total_final = Decimal(str(inv.get("total_amount_vnd") or 0))
                calc_total = pretax + vat

                if abs(calc_total - total_final) > Decimal("1.0000"):
                    findings.append(
                        {
                            "agent": "nam",
                            "severity": "error",
                            "table": "erp_invoices",
                            "record_id": inv_id,
                            "message": f"Hóa đơn [{inv.get('invoice_number')}] lệch số học VAT: Trước thuế ({pretax:,.0f}) + VAT ({vat:,.0f}) != Tổng ({total_final:,.0f}).",
                        }
                    )

                if needs_update:
                    with self._erp_client.get_connection() as conn:
                        with conn.cursor() as cur:
                            set_str = ", ".join([f"{k} = %s" for k in update_fields])
                            cur.execute(
                                f"UPDATE erp_invoices SET {set_str} WHERE id = %s;",
                                (*update_fields.values(), inv_id),
                            )
                            conn.commit()

                    self._erp_client.create_autonomous_healing_log(
                        {
                            "session_id": session_id,
                            "agent_code": "nam",
                            "table_name": "erp_invoices",
                            "record_id": inv_id,
                            "action_type": "align_pillar",
                            "snapshot_before": {"notes": current_notes},
                            "snapshot_after": update_fields,
                            "reason": "; ".join(reasons),
                            "confidence_score": 99,
                        }
                    )
                    healed += 1

        except Exception as exc:
            logger.error("[AUTONOMOUS] Lỗi heal_invoices_module: %s", exc)
            findings.append(
                {
                    "agent": "nam",
                    "severity": "error",
                    "table": "erp_invoices",
                    "message": f"Lỗi quét phân hệ hóa đơn: {exc}",
                }
            )

        return {
            "agent": "nam",
            "module": "invoices",
            "scanned": scanned,
            "healed": healed,
            "findings": findings,
        }
