from __future__ import annotations

import json
import logging
from typing import Any

logger = logging.getLogger(__name__)


class ErpTakeoffChatHistoryMixin:
    def save_takeoff_chat_message(
        self,
        takeoff_id: str,
        sender_role: str,
        sender_name: str,
        message_text: str,
        suggested_corrections: list[dict[str, Any]] | None = None,
        extracted_rules: list[dict[str, Any]] | None = None,
        applied: bool = False,
    ) -> dict[str, Any]:
        """Lưu tin nhắn hội thoại huấn luyện / phản hồi kỹ thuật của AI Quỳnh."""
        sql = """
            INSERT INTO erp_ai_takeoff_chat_messages (
                takeoff_id, sender_role, sender_name, message_text,
                suggested_corrections, extracted_rules, applied, created_at
            ) VALUES (
                %s, %s, %s, %s, %s, %s, %s, NOW()
            ) RETURNING *;
        """
        with self.get_connection() as conn, conn.cursor() as cur:
            cur.execute(
                sql,
                (
                    takeoff_id,
                    sender_role,
                    sender_name,
                    message_text,
                    json.dumps(suggested_corrections or [], default=str),
                    json.dumps(extracted_rules or [], default=str),
                    applied,
                ),
            )
            row = cur.fetchone()
            conn.commit()
            if row:
                row["id"] = str(row["id"])
                row["takeoff_id"] = str(row["takeoff_id"])
                row["message"] = row.get("message_text") or ""
                row["ai_response"] = row.get("message_text") or ""
                row["reply_message"] = row.get("message_text") or ""
                row["suggested_boq_items"] = suggested_corrections or []
                row["sender"] = row.get("sender_role") or "assistant"
                if row.get("created_at"):
                    row["created_at"] = row["created_at"].isoformat()
            return row

    def list_takeoff_chat_messages(self, takeoff_id: str) -> list[dict[str, Any]]:
        """Lấy toàn bộ lịch sử hội thoại huấn luyện của một hồ sơ bóc tách."""
        sql = """
            SELECT * FROM erp_ai_takeoff_chat_messages
            WHERE takeoff_id = %s
            ORDER BY created_at ASC;
        """
        with self.get_connection() as conn:
            with conn.cursor() as cur:
                cur.execute(sql, (takeoff_id,))
                rows = cur.fetchall()
                for r in rows:
                    if "id" in r and r["id"] is not None:
                        r["id"] = str(r["id"])
                    if "takeoff_id" in r and r["takeoff_id"] is not None:
                        r["takeoff_id"] = str(r["takeoff_id"])
                    if isinstance(r.get("suggested_corrections"), str):
                        try:
                            r["suggested_corrections"] = json.loads(
                                r["suggested_corrections"]
                            )
                        except Exception:
                            r["suggested_corrections"] = []
                    if isinstance(r.get("extracted_rules"), str):
                        try:
                            r["extracted_rules"] = json.loads(r["extracted_rules"])
                        except Exception:
                            r["extracted_rules"] = []

                    # Enriched alias fields for flawless frontend compatibility
                    msg_text = r.get("message_text") or ""
                    r["message"] = msg_text
                    r["ai_response"] = msg_text
                    r["reply_message"] = msg_text
                    r["suggested_boq_items"] = r.get("suggested_corrections") or []
                    r["sender"] = r.get("sender_role") or "assistant"
                    if r.get("created_at"):
                        r["created_at"] = r["created_at"].isoformat()
                return rows

    def clear_takeoff_chat_history(self, takeoff_id: str) -> bool:
        """Xóa toàn bộ lịch sử hội thoại huấn luyện của một hồ sơ bóc tách."""
        sql = "DELETE FROM erp_ai_takeoff_chat_messages WHERE takeoff_id = %s;"
        with self.get_connection() as conn, conn.cursor() as cur:
            cur.execute(sql, (takeoff_id,))
            conn.commit()
            return True
