import json
import logging
from common.llm_factory import create_llm
from config import DEFAULT_MODEL
from common.sqlite_db import sqlite_db
from common.constants import TABLE_FASHION_RULES

logger = logging.getLogger(__name__)

def generate_optimizer_prompt(feedbacks: list, current_rules: str) -> str:
    """
    Tạo prompt phân tích Feedback xấu và đề xuất Rule mới.
    """
    feedback_text = ""
    for idx, fb in enumerate(feedbacks):
        query = fb.get('query', '') or fb.get('user_query', '')
        response = fb.get('ai_response', '') or fb.get('bot_suggestion', '')
        note = fb.get('feedback_text', '') or fb.get('feedback_note', '')
        feedback_text += f"{idx+1}. User: '{query}' -> Bot: '{response}' -> Feedback chê: '{note}'\n"
        
    prompt = f"""
    You are an expert AI Fashion Quality Assurance (QA) Agent. 
    Your task is to fix logical flaws in the current rules based on user bad-feedback.
    
    =========== EXPLICIT INSTRUCTIONS ===========
    1. Check what the users are angry about in the feedback.
    2. Review the CURRENT RULES.
    3. Output JSON with fields: 'rule_type' (string, e.g., 'size_guide', 'policy', 'tone'), 'new_rule' (string), 'reasoning' (string), 'confidence' (float 0.0-1.0).
    4. Provide the FINAL COMPLETE JSON EXACTLY.

    =========== BAD FEEDBACK LOGS ===========
    {feedback_text}
    
    =========== CURRENT RULES ===========
    {current_rules}
    """
    return prompt

async def persist_new_rule(rule_data: dict) -> bool:
    """
    Persistent Memory Hook: Lưu Rule mới học được vào Database.
    Giống cơ chế Learning Loop của Hermes-Agent.
    """
    try:
        query = f"""
            INSERT INTO {TABLE_FASHION_RULES} (rule_type, rule_content, created_by, status)
            VALUES (?, ?, ?, 'active')
        """
        rule_type = rule_data.get('rule_type', 'general')
        rule_content = f"{rule_data.get('new_rule', '')} (Lý do: {rule_data.get('reasoning', '')})"
        
        await sqlite_db.execute(query, (rule_type, rule_content, "feedback_learning_loop"))
        logger.info(f"Đã lưu Rule mới vào não bộ: {rule_content[:50]}...")
        return True
    except Exception as e:
        logger.error(f"Lỗi khi lưu Persistent Memory: {e}")
        return False

async def run_optimization_logic(feedbacks: list, current_rules_str: str) -> str:
    """
    Lõi chạy suy luận trực tiếp bằng LLM và ghi nhớ.
    """
    logger.info("Chạy Agent Learning Loop phân tích Rules vs Feedbacks bằng LLM...")
    
    prompt = generate_optimizer_prompt(feedbacks, current_rules_str)
    llm = create_llm(DEFAULT_MODEL, json_mode=True)
    messages = [{"role": "system", "content": "You output JSON strictly."}, {"role": "user", "content": prompt}]
    
    try:
        response = await llm.ainvoke(messages)
        content = response.content
        # Remove any markdown formatting if present
        if content.startswith("```json"):
            content = content.replace("```json", "").replace("```", "").strip()
            
        data = json.loads(content)
        
        # Validation
        if len(data.get("new_rule", "")) < 10 or data.get("confidence", 0.0) < 0.3:
            logger.warning("Rejected rule from LLM: confidence too low or rule too short")
            return "{}"
            
        # Hook: Persistent Memory
        await persist_new_rule(data)
            
        return json.dumps(data, ensure_ascii=False, indent=4)
    except Exception as e:
        logger.error(f"Failed to parse optimization logic output: {e}")
        return "{}"
