from __future__ import annotations

import logging
import re
from typing import Any

logger = logging.getLogger("dscons.autonomous.documents")


class HealDocumentsMixin:
    """Self-healing routines for pending/quarantined project documents."""

    def heal_documents_module(self, session_id: str) -> dict[str, Any]:
        """Tự chuẩn hóa bảng documents: Làm sạch trích yếu, kiểm tra MST, cập nhật audit readiness và liên kết dự án."""
        logger.info(
            "[AUTONOMOUS] AI Thảo & Thủy bắt đầu quét phân hệ Hồ Sơ & Văn Bản..."
        )
        from app.modules.core.application.document_processing_service import DocumentProcessingService

        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, document_code, document_title, document_type, document_group,
                               issuer_name, partner_name, partner_tax_code, issue_date,
                               signature_status, audit_readiness_score, verification_status,
                               status, project_id, file_path
                        FROM erp_documents
                        ORDER BY created_at DESC
                        LIMIT 100;
                    """)
                    docs = cur.fetchall()

            scanned = len(docs)
            for doc in docs:
                doc_id = str(doc["id"])
                original_title = doc.get("document_title") or ""
                clean_title = DocumentProcessingService.sanitize_document_title(
                    original_title
                )

                needs_update = False
                update_fields: dict[str, Any] = {}
                reasons: list[str] = []

                # 1.1. Làm sạch trích yếu nếu có ký tự rác / nhãn hệ thống
                if clean_title != original_title:
                    update_fields["document_title"] = clean_title
                    reasons.append("Làm sạch trích yếu loại bỏ nhãn bảo mật thừa")
                    needs_update = True

                # 1.2. Chuẩn hóa Audit Readiness Score dựa trên trạng thái chữ ký
                sig_status = doc.get("signature_status") or "draft"
                expected_audit_score = (
                    100
                    if sig_status == "fully_executed"
                    else (75 if sig_status == "signed_unsigned_seal" else 50)
                )
                current_audit_score = doc.get("audit_readiness_score")
                if current_audit_score != expected_audit_score:
                    update_fields["audit_readiness_score"] = expected_audit_score
                    reasons.append(
                        f"Cập nhật Audit Score từ {current_audit_score} lên {expected_audit_score}"
                    )
                    needs_update = True

                # 1.3. Chuẩn hóa verification_status nếu đang processing mà đã có dữ liệu
                if (
                    doc.get("verification_status") in ["processing", None]
                    and clean_title
                ):
                    update_fields["verification_status"] = "pending_review"
                    if doc.get("status") in ["processing", None]:
                        update_fields["status"] = "pending_review"
                    reasons.append(
                        "Chuyển trạng thái sang pending_review sau khi hoàn tất trích xuất"
                    )
                    needs_update = True

                # 1.4. Kiểm tra MST đối tác
                tax_code = doc.get("partner_tax_code")
                if tax_code and not re.match(
                    r"^\d{10}(-\d{3})?$", str(tax_code).strip()
                ):
                    findings.append(
                        {
                            "agent": "thao",
                            "severity": "warning",
                            "table": "erp_documents",
                            "record_id": doc_id,
                            "message": f"Văn bản [{doc.get('document_code')}] có MST đối tác '{tax_code}' không đúng chuẩn 10/13 số.",
                        }
                    )

                # Thực thi cập nhật nếu có trường thay đổi
                if needs_update:
                    self._erp_client.update_document(doc_id, update_fields)
                    self._erp_client.create_autonomous_healing_log(
                        {
                            "session_id": session_id,
                            "agent_code": "thao",
                            "table_name": "erp_documents",
                            "record_id": doc_id,
                            "action_type": "normalize_metadata",
                            "snapshot_before": {k: doc.get(k) for k in update_fields},
                            "snapshot_after": update_fields,
                            "reason": "; ".join(reasons),
                            "confidence_score": 98,
                        }
                    )
                    healed += 1

                # 1.5. Tự động liên kết / tạo dự án từ TBMT nếu chưa gán project_id
                doc_type = doc.get("document_type") or ""
                if not doc.get("project_id") and (
                    doc_type in ["TB", "QD", "HD"]
                    or "mời thầu" in clean_title.lower()
                    or "dự án" in clean_title.lower()
                ):
                    try:
                        proj_res = self._erp_client.create_project_from_document(doc_id)
                        if proj_res.get("project_id"):
                            findings.append(
                                {
                                    "agent": "minh",
                                    "severity": "info",
                                    "table": "projects",
                                    "record_id": str(proj_res["project_id"]),
                                    "message": f"Tự động liên kết Dự án [{proj_res.get('project_code')}] từ văn bản TBMT.",
                                }
                            )
                    except Exception as e:
                        logger.debug("Bỏ qua tự tạo dự án cho doc_id=%s: %s", doc_id, e)

        except Exception as exc:
            logger.error("[AUTONOMOUS] Lỗi heal_documents_module: %s", exc)
            findings.append(
                {
                    "agent": "thao",
                    "severity": "error",
                    "table": "erp_documents",
                    "message": f"Lỗi quét phân hệ hồ sơ: {exc}",
                }
            )

        return {
            "agent": "thao",
            "module": "documents",
            "scanned": scanned,
            "healed": healed,
            "findings": findings,
        }
