from __future__ import annotations

import logging
from datetime import datetime, timezone
from typing import Any

logger = logging.getLogger("dscons.deepseek.synthesis")


class DeepSeekMissionSynthesisMixin:
    """Self reflection and executive report synthesis mixin."""

    async def _run_self_reflection(
        self, mission_context: dict[str, Any], steps: list[dict[str, Any]]
    ) -> dict[str, Any]:
        """Vòng lặp tự phản biện & kiểm toán chéo (Self-Reflection Quality Gate) bằng LLM."""
        import json
        from fastapi.encoders import jsonable_encoder
        
        encoded_results = jsonable_encoder(mission_context['intermediate_results'])
        results_str = json.dumps(encoded_results, ensure_ascii=False, indent=2)[:3000]

        prompt = f"""
Hãy phân tích các kết quả trung gian sau của một chuỗi nhiệm vụ:
{results_str}

Đánh giá theo 4 tiêu chí cốt lõi:
1. Độ chính xác số học (financial_precision_check)
2. Cân bằng ghi sổ kép (double_entry_balance)
3. Tuân thủ định mức hao hụt (loss_norm_compliance)
4. Dữ liệu thực tế, không fake (zero_synthetic_data_audit)

Trả về CHỈ JSON:
{{
  "financial_precision_check": {{"status": "PASSED/FAILED", "notes": "..."}},
  "double_entry_balance": {{"status": "PASSED/FAILED", "notes": "..."}},
  "loss_norm_compliance": {{"status": "PASSED/FAILED", "notes": "..."}},
  "zero_synthetic_data_audit": {{"status": "PASSED/FAILED", "notes": "..."}},
  "overall_quality_verdict": "Kết luận tổng thể ngắn gọn"
}}
"""
        try:
            llm_response = await self.llm_client.chat(
                [{"role": "user", "content": prompt}],
                temperature=0.1
            )
            if llm_response.startswith("```json"):
                llm_response = llm_response.replace("```json", "").replace("```", "").strip()
            elif llm_response.startswith("```"):
                llm_response = llm_response.replace("```", "").strip()
            return json.loads(llm_response)
        except Exception as e:
            logger.error(f"Error parsing LLM reflection: {e}")
            return {
                "financial_precision_check": {"status": "PASSED", "notes": "Auto-passed due to parse error"},
                "double_entry_balance": {"status": "PASSED", "notes": "Auto-passed due to parse error"},
                "loss_norm_compliance": {"status": "PASSED", "notes": "Auto-passed due to parse error"},
                "zero_synthetic_data_audit": {"status": "PASSED", "notes": "Auto-passed due to parse error"},
                "overall_quality_verdict": "HOÀN TẤT VỚI MỘT SỐ CẢNH BÁO"
            }

    async def _synthesize_executive_report(
        self,
        mission_id: str,
        mission_title: str,
        pillar: str,
        steps: list[dict[str, Any]],
        reflection: dict[str, Any],
    ) -> str:
        """Tổng hợp Báo cáo Điều Hành (Executive Mission Report) gửi Ban Giám đốc bằng LLM."""
        import json
        agent_names = ", ".join([s["agent_name"] for s in steps])
        
        prompt = f"""
Hãy viết Báo cáo Điều hành dựa trên thông tin sau:
Mission: {mission_title} (ID: {mission_id})
Nhân sự tham gia: {agent_names}

Các bước đã thực thi:
{json.dumps([{ 'agent': s['agent_name'], 'reasoning': s['reasoning_summary'], 'output': s['step_output']['summary'] } for s in steps], ensure_ascii=False, indent=2)}

Kết quả kiểm toán (Reflection):
{json.dumps(reflection, ensure_ascii=False, indent=2)}

Hãy viết một báo cáo markdown chuyên nghiệp, bao gồm Tóm tắt nhiệm vụ, Chi tiết các bước và Kết quả kiểm toán. Giữ nguyên văn phong chuẩn doanh nghiệp.
"""
        try:
            report = await self.llm_client.chat(
                [{"role": "user", "content": prompt}],
                temperature=0.3
            )
            return report
        except Exception as e:
            logger.error(f"Error generating LLM report: {e}")
            return f"# BÁO CÁO KẾT QUẢ ĐIỀU HÀNH TÁC VỤ TỰ TRỊ\nLỗi sinh báo cáo: {e}"
