"""
小红书 AI 内容助手 - OpenClaw 深度集成模块

实现功能：
1. 自然语言解析
2. 多轮对话优化
3. 内容资产管理
4. 自动迭代优化
"""

import re
import json
from typing import Dict, List, Optional, Tuple
from datetime import datetime
from pathlib import Path

# 导入核心模块
import sys
sys.path.insert(0, str(Path(__file__).parent))
from models import OpenAICompatibleProvider
from core import ContentGenerator, TemplateManager
from config import settings


class IntentParser:
    """意图解析器 - 理解用户需求"""

    # 内容类型关键词映射
    TYPE_KEYWORDS = {
        "coffee_culture": ["咖啡", "手冲", "探店", "咖啡馆", "coffee", "拿铁", "美式", "latte"],
        "product_review": ["产品", "测评", "推荐", "种草", "好物", "使用", "体验"],
        "ootd": ["穿搭", "搭配", "衣服", "OOTD", "时尚", "风格", "造型"],
        "lifestyle": ["日常", "生活", "分享", "记录", "vlog", "碎片"],
        "food": ["美食", "餐厅", "探店", "菜谱", "好吃", "餐厅"],
        "travel": ["旅行", "旅游", "攻略", "景点", "打卡", "度假"],
        "knowledge": ["知识", "科普", "干货", "教程", "方法", "技巧"]
    }

    # 风格关键词
    STYLE_KEYWORDS = {
        "轻松活泼": ["轻松", "活泼", "愉快", "快乐"],
        "文艺清新": ["文艺", "清新", "治愈", "温柔"],
        "幽默风趣": ["幽默", "搞笑", "有趣", "好玩"],
        "专业干货": ["专业", "干货", "详细", "深入"],
        "温馨治愈": ["温馨", "治愈", "温暖", "感人"]
    }

    def parse(self, user_input: str) -> Dict:
        """
        解析用户输入，提取意图

        Args:
            user_input: 用户输入的自然语言

        Returns:
            解析结果字典
        """
        result = {
            "topic": "",
            "content_type": "lifestyle",
            "style": "轻松活泼",
            "params": {},
            "confidence": 0.0
        }

        # 提取主题
        result["topic"] = self._extract_topic(user_input)

        # 识别内容类型
        result["content_type"] = self._detect_content_type(user_input)

        # 识别风格
        result["style"] = self._detect_style(user_input)

        # 计算置信度
        result["confidence"] = self._calculate_confidence(user_input, result)

        return result

    def _extract_topic(self, text: str) -> str:
        """提取主题"""
        # 移除常见的开头词
        patterns = [
            r"^(写|生成|帮我|关于|一篇|一个)",
            r"(小红书|文案|笔记|内容).*"
        ]

        topic = text
        for pattern in patterns:
            topic = re.sub(pattern, "", topic, flags=re.IGNORECASE)

        return topic.strip("的？？?!！。,，")

    def _detect_content_type(self, text: str) -> str:
        """检测内容类型"""
        text_lower = text.lower()

        for content_type, keywords in self.TYPE_KEYWORDS.items():
            for keyword in keywords:
                if keyword in text_lower:
                    return content_type

        return "lifestyle"

    def _detect_style(self, text: str) -> str:
        """检测风格"""
        for style, keywords in self.STYLE_KEYWORDS.items():
            for keyword in keywords:
                if keyword in text:
                    return style
        return "轻松活泼"

    def _calculate_confidence(self, text: str, result: Dict) -> float:
        """计算置信度"""
        score = 0.5

        # 有明确主题
        if result["topic"]:
            score += 0.3

        # 有明确类型
        if result["content_type"] != "lifestyle":
            score += 0.1

        # 有明确风格
        if result["style"] != "轻松活泼":
            score += 0.1

        return min(score, 1.0)


class ConversationManager:
    """对话管理器 - 多轮对话优化"""

    def __init__(self):
        self.context = {}
        self.history = []

    def add_message(self, role: str, content: str):
        """添加对话历史"""
        self.history.append({
            "role": role,
            "content": content,
            "timestamp": datetime.now().isoformat()
        })

    def get_context(self, key: str = None) -> any:
        """获取上下文"""
        if key:
            return self.context.get(key)
        return self.context

    def update_context(self, key: str, value: any):
        """更新上下文"""
        self.context[key] = value

    def clear(self):
        """清空对话"""
        self.context = {}
        self.history = []

    def suggest_questions(self, current_state: Dict) -> List[str]:
        """建议追问"""
        suggestions = []

        # 根据缺失信息建议追问
        if not current_state.get("topic"):
            suggestions.append("请问你想写什么主题的内容？")

        if current_state.get("content_type") == "coffee_culture":
            if not current_state.get("params", {}).get("cafe_scenario"):
                suggestions.append("是什么场景？(独自工作/闺蜜聚会/约会)")

        if current_state.get("content_type") == "product_review":
            if not current_state.get("params", {}).get("product_name"):
                suggestions.append("请问是什么产品？")

        return suggestions


class ContentAssetManager:
    """内容资产管理器"""

    def __init__(self, storage_path: str = None):
        self.storage_path = storage_path or "./content_assets"
        Path(self.storage_path).mkdir(exist_ok=True)

    def save(self, content: Dict, user_id: str = "default") -> str:
        """保存内容"""
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"{user_id}_{timestamp}.json"
        filepath = Path(self.storage_path) / filename

        data = {
            "user_id": user_id,
            "timestamp": datetime.now().isoformat(),
            "content": content
        }

        with open(filepath, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

        return str(filepath)

    def search(self, user_id: str = "default", keyword: str = "",
               content_type: str = "", limit: int = 10) -> List[Dict]:
        """搜索历史内容"""
        results = []

        for filepath in Path(self.storage_path).glob(f"{user_id}_*.json"):
            try:
                with open(filepath, "r", encoding="utf-8") as f:
                    data = json.load(f)

                # 筛选条件
                if keyword and keyword not in str(data):
                    continue
                if content_type and data.get("content", {}).get("content_type") != content_type:
                    continue

                results.append(data)
            except Exception:
                continue

        return results[:limit]

    def analyze(self, user_id: str = "default") -> Dict:
        """分析用户内容"""
        contents = self.search(user_id)

        if not contents:
            return {"message": "暂无历史内容"}

        # 统计分析
        type_count = {}
        total_count = len(contents)

        for content in contents:
            ct = content.get("content", {}).get("content_type", "unknown")
            type_count[ct] = type_count.get(ct, 0) + 1

        # 最常用的类型
        most_used_type = max(type_count.items(), key=lambda x: x[1])[0] if type_count else "unknown"

        return {
            "total_count": total_count,
            "type_distribution": type_count,
            "most_used_type": most_used_type,
            "recent_contents": contents[:5]
        }


class AutoOptimizer:
    """自动优化器 - 迭代优化内容"""

    def __init__(self, llm_provider, generator: ContentGenerator):
        self.llm = llm_provider
        self.generator = generator

    def optimize_loop(
        self,
        topic: str,
        content_type: str,
        max_iterations: int = 3,
        target_score: float = 8.0
    ) -> Dict:
        """
        迭代优化循环

        Args:
            topic: 主题
            content_type: 内容类型
            max_iterations: 最大迭代次数
            target_score: 目标分数

        Returns:
            优化结果
        """
        best_content = None
        best_score = 0
        history = []

        for i in range(max_iterations):
            # 生成内容
            if i == 0:
                # 第一次使用原始主题
                current_topic = topic
            else:
                # 后续根据反馈优化
                current_topic = self._refine_topic(topic, best_content, best_score)

            result = self.generator.generate(
                content_type=content_type,
                params={"topic": current_topic},
                temperature=0.7 + (i * 0.1)
            )

            # 评分
            score = self._score_content(result)
            history.append({
                "iteration": i + 1,
                "score": score,
                "content": result
            })

            # 更新最佳
            if score > best_score:
                best_score = score
                best_content = result

            # 达到目标分数
            if score >= target_score:
                break

        return {
            "best_content": best_content,
            "best_score": best_score,
            "iterations": len(history),
            "history": history
        }

    def _score_content(self, content: Dict) -> float:
        """内容评分"""
        score = 5.0  # 基础分

        # 标题评分
        title = content.get("title", "")
        if len(title) > 10 and len(title) < 50:
            score += 1.0

        # 内容长度评分
        word_count = content.get("word_count", 0)
        if 200 <= word_count <= 800:
            score += 1.5

        # 标签评分
        tags = content.get("tags", [])
        if 5 <= len(tags) <= 10:
            score += 1.0

        # 真人感评分（简单检测）
        content_text = content.get("content", "")
        if any(word in content_text for word in ["我", "感觉", "发现", "有点"]):
            score += 1.5

        return min(score, 10.0)

    def _refine_topic(self, original_topic: str, content: Dict, score: float) -> str:
        """根据评分优化主题描述"""
        if score < 6.0:
            return f"{original_topic}，增加更多细节和个人感受"
        elif score < 8.0:
            return f"{original_topic}，让表达更口语化、更有代入感"
        else:
            return original_topic


class OpenClawAgent:
    """OpenClaw 智能代理 - 主入口"""

    def __init__(self, api_key: str = None, base_url: str = None, model: str = None):
        """
        初始化代理
        
        Args:
            api_key: 通义千问 API Key（可选，不传则使用环境变量/配置文件）
            base_url: API Base URL（可选）
            model: 模型名称（可选）
        """
        # 支持动态传入 API Key
        if api_key:
            settings.set_api_key(api_key, base_url, model)
        
        # 初始化组件
        self.llm = OpenAICompatibleProvider(
            api_key=settings.API_KEY,
            base_url=settings.API_BASE_URL,
            model=settings.MODEL
        )
        self.generator = ContentGenerator(self.llm)
        self.intent_parser = IntentParser()
        self.conversation = ConversationManager()
        self.asset_manager = ContentAssetManager()
        self.optimizer = AutoOptimizer(self.llm, self.generator)

    def process(self, user_input: str, user_id: str = "default") -> Dict:
        """
        处理用户输入

        Args:
            user_input: 用户输入
            user_id: 用户ID

        Returns:
            处理结果
        """
        # 记录用户输入
        self.conversation.add_message("user", user_input)

        # 解析意图
        intent = self.intent_parser.parse(user_input)

        # 如果置信度低，需要追问
        if intent["confidence"] < 0.7:
            suggestions = self.conversation.suggest_questions(intent)
            return {
                "status": "need_more_info",
                "message": "我需要更多信息来帮你生成内容",
                "suggestions": suggestions,
                "current_intent": intent
            }

        # 生成内容
        try:
            result = self.generator.generate(
                content_type=intent["content_type"],
                params={"topic": intent["topic"]},
                style=intent["style"]
            )

            # 保存到资产库
            self.asset_manager.save(result, user_id)

            # 记录助手回复
            self.conversation.add_message("assistant", result.get("content", ""))

            return {
                "status": "success",
                "content": result,
                "intent": intent
            }

        except Exception as e:
            return {
                "status": "error",
                "message": str(e)
            }

    def optimize(self, content: str, instruction: str) -> Dict:
        """优化内容"""
        try:
            optimized = self.generator.optimize(content, instruction)
            return {
                "status": "success",
                "original": content,
                "optimized": optimized
            }
        except Exception as e:
            return {
                "status": "error",
                "message": str(e)
            }

    def auto_optimize(self, topic: str, content_type: str) -> Dict:
        """自动迭代优化"""
        return self.optimizer.optimize_loop(topic, content_type)

    def get_history(self, user_id: str = "default") -> Dict:
        """获取用户历史"""
        return self.asset_manager.analyze(user_id)

    def clear_conversation(self):
        """清空对话"""
        self.conversation.clear()


# ============================================
# 使用示例
# ============================================

if __name__ == "__main__":
    agent = OpenClawAgent()

    # 示例 1：简单生成
    print("=== 示例 1：简单生成 ===")
    result = agent.process("帮我写一篇关于周末咖啡探店的文案")
    if result["status"] == "success":
        print(result["content"]["content"])

    # 示例 2：自动优化
    print("\n=== 示例 2：自动优化 ===")
    result = agent.auto_optimize("手冲咖啡入门", "coffee_culture")
    print(f"最佳分数: {result['best_score']}")
    print(result["best_content"]["content"])

    # 示例 3：查看历史
    print("\n=== 示例 3：查看历史 ===")
    history = agent.get_history()
    print(f"总内容数: {history['total_count']}")
    print(f"最常用类型: {history['most_used_type']}")
