"""
Director Agent
专用于 Creative Studio 的制片人 Agent
"""
from pathlib import Path
from typing import Optional
from .agent import LangChainSkillsAgent
from .context import SkillAgentContext

class DirectorAgent(LangChainSkillsAgent):
    """
    Director Agent 继承自 LangChainSkillsAgent
    使用专门的 System Prompt 和工具集来支持 Agent-Native 协作模式
    """

    def __init__(
        self,
        working_directory: Optional[Path] = None,
        enable_thinking: bool = True,
        model: Optional[str] = None,
        project_context: Optional[SkillAgentContext] = None,
    ):
        """
        初始化 Director Agent

        Args:
            working_directory: 工作目录
            enable_thinking: 是否启用思考模式
            model: 模型名称
            project_context: 项目上下文（可选）
        """
        # 保存项目上下文引用
        self._project_context = project_context

        # 调用父类初始化
        super().__init__(
            working_directory=working_directory,
            enable_thinking=enable_thinking,
            model=model,
        )

        # 确保 context 属性存在（防御性检查）
        # 父类应该已经创建了 self.context，但为了防止某些边界情况，这里再次确认
        if not hasattr(self, 'context') or self.context is None:
            from .skill_loader import SkillLoader
            self.context = SkillAgentContext(
                skill_loader=self.skill_loader,
                working_directory=self.working_directory,
            )

        # 如果提供了项目上下文，更新 context
        if project_context:
            self.context = project_context
            # 重新构建 system prompt 并刷新 agent
            self.system_prompt = self._build_system_prompt()
            self.refresh_agent()

    def refresh_agent(self):
        """重新构建 LangChain Agent 以应用新的 System Prompt"""
        self.agent = self._create_agent()

    def _build_system_prompt(self) -> str:
        # 基础 prompt
        base_prompt = """You are the AI Producer & Head Writer for a creative studio.
The User is the Director. Your goal is to help the Director create high-quality series content.

## Your Role
- **Proactive Partner**: Don't just wait for orders. Propose plans, spot issues, and suggest improvements.
- **Series Manager**: You are responsible for the entire series. You can list all episodes, focus on specific ones, and save/update their content.
- **Structured Executor**: For any complex task (like "Write the whole series" or "Write Episode 1"), you MUST first create a Plan using `update_plan`.
- **Transparent**: Always keep the Director informed of your status via the plan and inbox.

## Workflow Protocols

1. **Planning (Mandatory for new tasks)**
   - When receiving a high-level goal (e.g., "Write all scripts"), break it down into episodes and steps.
   - Use `update_plan(steps=[...], current_step=0, status='planning')`.

2. **Episode Creation (IMPORTANT)**
   - When the Director says "开始创作第X集" or "开始创作 EP X" or similar:
     - Use `create_episode(episode_number=X)` tool to start the creation process
     - This tool will automatically: analyze previous memory, generate outline, write dialogue, review, and update memory
     - The creation runs in the background and updates will be sent via WebSocket
     - The Director will see progress in the plan panel and final content on the canvas

3. **Execution & Writing**
   - Use `list_episodes` to see the current progress of the project.
   - Use `focus_episode` to navigate between episodes. This will update the user's view.
   - **Canvas Focus**: The main canvas is for the **actual script/dialogue content**. Do NOT put outlines on the canvas unless specifically asked.
   - **Outline Location**: Episode-level outlines should be stored in the episode's `outline` field via `save_episode` or `update_episode`. Global outlines are in the project context.
   - Use `write_to_canvas` to show the draft script you are working on.
   - Use `save_episode` (for completion) or `update_episode` (for partial updates) to persist content to the database.
   - Update your plan status as you progress: `update_plan(..., status='writing')`.

4. **AI Editing & Optimization (CRITICAL)**
   - When the Director asks you to "optimize", "improve", "edit", or "revise" content, you MUST:
     1. Process the content to improve it based on the request
     2. Use `write_to_canvas(content="IMPROVED_FULL_CONTENT", append=false)` to replace the canvas content
     3. Do NOT just output text - you must use the tool to update the canvas
   - When asked to "优化", "改进", "编辑", or "修改" content, same rules apply
   - Example: If asked to optimize Episode 1, call `write_to_canvas(content="<optimized script>", append=false)`
   - Always use append=false when doing full content replacement
   - This is the ONLY way to properly update the canvas for the user to see

5. **Review & Approval**
   - NEVER mark a major deliverable as "Final" without Director approval.
   - Use `add_inbox_task` to submit drafts or questions to the Director.
   - Example: `add_inbox_task(title="Review Episode 1 Outline", type="review", ...)`

6. **Context & Memory**
   - If the story state changes (e.g., location change, character injury), use `update_context`.
   - If you spot consistency issues, use `add_annotation` on the canvas.

## Interaction Style
- Be professional, creative, and concise.
- Use the Director's language (Chinese/English) matching their input.
- When you are working, keep the plan updated.
- CRITICAL: When asked to edit/optimize content, ALWAYS use `write_to_canvas` tool with append=false to replace content, don't just output text.
- CRITICAL: When asked to create episodes, use `create_episode` tool which runs in background and doesn't block the interface.
"""

        # 添加项目上下文（如果有）
        context = getattr(self, 'context', None)
        if context and context.project_name:
            base_prompt += "\n\n## Project Context\n\n"
            base_prompt += f"**Project**: {context.project_name}\n"

            if context.project_genre:
                base_prompt += f"**Genre**: {context.project_genre}\n"

            if context.total_episodes:
                base_prompt += f"**Total Episodes**: {context.total_episodes}\n"

            base_prompt += "\n### Global Settings\n\n"

            if context.world_setting:
                base_prompt += f"**World Setting**:\n{context.world_setting}\n\n"

            if context.characters:
                base_prompt += f"**Characters**:\n{context.characters}\n\n"

            if context.overall_outline:
                base_prompt += f"**Overall Outline**:\n{context.overall_outline}\n\n"

            if context.source_content:
                mode = "剧本改编" if context.creation_mode == "script" else "创意灵感"
                base_prompt += f"**Source** ({mode}):\n{context.source_content[:1000]}...\n\n"

        # 添加当前剧集信息
        if context and context.active_episode_number:
            base_prompt += "## Current Task Focus\n\n"
            base_prompt += f"You are currently focusing on **Episode {context.active_episode_number}**"
            if context.active_episode_title:
                base_prompt += f": {context.active_episode_title}"
            base_prompt += ".\n"
            base_prompt += "Your primary goal is to generate or refine content for THIS SPECIFIC episode based on the global context provided above.\n\n"

        # 构建 skills prompt
        skills_prompt = self.skill_loader.build_system_prompt("")

        # 添加用户配置的 skills
        if context and context.user_skills:
            skills_prompt += "\n\n### User Configured Skills\n\n"
            skills_prompt += "The Director has configured these specific skills for this project:\n\n"
            for skill in context.user_skills:
                skills_prompt += f"- **{skill.get('name', 'Unknown')}**: {skill.get('behavior', 'No description')}\n"
            skills_prompt += "\nUse `load_skill` to load detailed instructions for these skills when relevant.\n"

        return base_prompt + "\n\n" + skills_prompt
