"""
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
        if project_context:
            self.context = project_context
            # 重新构建 system prompt
            self.system_prompt = self._build_system_prompt()

    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.
- **Structured Executor**: For any complex task (like "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 Scene 1"), break it down into steps.
   - Use `update_plan(steps=[...], current_step=0, status='planning')`.

2. **Execution & Writing**
   - Use `write_file` to generate content.
   - Use `update_canvas` (or write to the active file) to show progress.
   - Update your plan status as you progress: `update_plan(..., status='writing')`.

3. **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", ...)`

4. **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.
"""

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

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

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

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

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

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

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

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

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

        # 添加用户配置的 skills
        if self.context and self.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 self.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
