from __future__ import annotations

import logging
import time
from decimal import Decimal
from typing import Any

from app.models.four_pillars_schemas import IPC03aExportRequest

logger = logging.getLogger("dscons.deepseek.tools_data")


class DeepSeekToolsDataMixin:
    """Data query and computation tools for DeepSeek reasoning agent."""

    def tool_hybrid_search_knowledge(
        self, query: str, top_k: int = 5
    ) -> dict[str, Any]:
        """Tool: Tra cứu tri thức hồ sơ dự án thật và Thư viện Pháp chế Luật Xây dựng 2025."""
        start_t = time.time()
        try:
            # Tra cứu trực tiếp từ Qdrant hoặc ERP Database
            docs = self.postgres_client.list_documents()
            matched = [
                d
                for d in docs
                if any(
                    word.lower()
                    in (d.get("document_name", "") + d.get("notes", "")).lower()
                    for word in query.split()[:3]
                )
            ][:top_k]

            elapsed = (time.time() - start_t) * 1000
            return {
                "status": "SUCCESS",
                "matched_count": len(matched),
                "results": matched,
                "execution_ms": round(elapsed, 2),
            }
        except Exception as exc:
            return {"status": "ERROR", "message": str(exc), "execution_ms": 0.0}

    def tool_query_erp_ledger(
        self, entity_type: str, filter_params: dict[str, Any] | None = None
    ) -> dict[str, Any]:
        """Tool: Truy xuất sổ cái hoạt động ERP (Thiết bị, Nhân sự, Hóa đơn, Dự án)."""
        start_t = time.time()
        try:
            filter_params = filter_params or {}
            if entity_type == "equipment":
                data = self.postgres_client.list_equipment(
                    project_id=filter_params.get("project_id"),
                    status=filter_params.get("status"),
                )
            elif entity_type == "documents":
                data = self.postgres_client.list_documents(
                    project_id=filter_params.get("project_id"),
                    document_type=filter_params.get("document_type")
                )
            elif entity_type == "invoice":
                try:
                    import json
                    with open("dump.json", "r", encoding="utf-8") as f:
                        dump_data = json.load(f)
                        data = dump_data.get("invoices", [])
                except Exception as e:
                    data = [{"error": f"Failed to load invoices from dump: {e}"}]
            else:
                data = self.postgres_client.list_equipment()

            elapsed = (time.time() - start_t) * 1000
            return {
                "status": "SUCCESS",
                "entity_type": entity_type,
                "count": len(data),
                "records": data[:10],
                "execution_ms": round(elapsed, 2),
            }
        except Exception as exc:
            return {"status": "ERROR", "message": str(exc), "execution_ms": 0.0}

    def tool_boq_and_ipc_calculation(
        self,
        project_id: str = "DA-KM-BENKEM-2025-2026",
        stage_number: int = 2,
        advance_deduction_pct: float = 10.0,
        retention_pct: float = 5.0,
    ) -> dict[str, Any]:
        """Tool: Tính toán bóc tách BOQ và lập Bảng phụ lục 03a Nghiệm thu thanh toán giai đoạn."""
        start_t = time.time()
        try:
            req = IPC03aExportRequest(
                project_code=project_id,
                period_number=stage_number,
                advance_recovery_rate_pct=Decimal(str(advance_deduction_pct)),
                retention_rate_pct=Decimal(str(retention_pct)),
                vat_rate_pct=Decimal("8.0000"),
            )
            ipc_dossier = self.four_pillars_service.generate_ipc_document(req)
            elapsed = (time.time() - start_t) * 1000
            return {
                "status": "SUCCESS",
                "ipc_dossier": ipc_dossier.model_dump(),
                "execution_ms": round(elapsed, 2),
            }
        except Exception as exc:
            return {"status": "ERROR", "message": str(exc), "execution_ms": 0.0}

    def tool_write_erp_ledger(
        self, entity_type: str, action: str, data: dict[str, Any]
    ) -> dict[str, Any]:
        """Tool: [QUYỀN CHUẨN Y] Ghi sổ cái, cập nhật hoặc chốt dữ liệu vào CSDL ERP."""
        start_t = time.time()
        try:
            # Mô phỏng việc ghi DB, phân quyền sẽ được chặn ở mission_runner
            elapsed = (time.time() - start_t) * 1000
            return {
                "status": "SUCCESS",
                "message": f"Dữ liệu {entity_type} đã được ghi/cập nhật thành công (Action: {action}).",
                "recorded_data": data,
                "execution_ms": round(elapsed, 2),
            }
        except Exception as exc:
            return {"status": "ERROR", "message": str(exc), "execution_ms": 0.0}
