from typing import AsyncIterator, Optional, List
from pathlib import Path
from langchain_core.messages import BaseMessage

from app.core.skills.skill_manager import skill_manager
from app.core.agent_runtime.agent import LangChainSkillsAgent  # 假设移植后的路径

class CreativeStudioAgent:
    """
    Creative Studio 的 Agent 适配器
    将 LangChainSkillsAgent 集成到现有的后端架构中
    """
    
    def __init__(self, working_dir: str):
        self.working_dir = Path(working_dir)
        # 初始化底层的 LangChainSkillsAgent
        self.agent = LangChainSkillsAgent(
            working_directory=self.working_dir,
            enable_thinking=True
        )
        
        # 注入 SkillManager 的能力
        # 注意：这里我们覆盖默认的 skill_loader，改用 skill_manager
        self._inject_skills_from_manager()

    def _inject_skills_from_manager(self):
        """
        从 SkillManager 获取 Skills 并注入到 Agent 的 System Prompt
        """
        # 获取所有 Skills (内置 + 用户)
        # 这里需要 sync 包装或者改造 agent 支持 async init
        # 简化演示：假设我们构建了一个类似的 prompt
        pass

    async def chat_stream(self, message: str, thread_id: str) -> AsyncIterator[dict]:
        """
        流式对话接口
        适配前端所需的 WebSocket 消息格式
        """
        async for event in self.agent.stream_events(message, thread_id):
            # 转换为前端协议
            if event["type"] == "thinking":
                yield {"type": "thinking", "content": event["content"]}
            elif event["type"] == "text":
                yield {"type": "content", "content": event["content"]}
            elif event["type"] == "tool_call":
                yield {
                    "type": "tool_start", 
                    "tool": event["name"], 
                    "input": event["args"]
                }
            elif event["type"] == "tool_result":
                yield {
                    "type": "tool_end", 
                    "tool": event["name"], 
                    "output": event["content"]
                }
            elif event["type"] == "done":
                yield {"type": "done"}

    async def run_task(self, task_description: str):
        """
        执行特定任务（非对话模式）
        替代原本硬编码的 Service 逻辑
        """
        result = await self.agent.invoke(task_description)
        return result
