from typing import Optional
from pathlib import Path
from loguru import logger

from autocoder.common.v2.agent.agentic_edit_tools.base_tool_resolver import (
    BaseToolResolver,
)
from autocoder.common.v2.agent.agentic_edit_types import (
    ToolResult,
    LoadExtraDocumentTool,
)
from autocoder.common import AutoCoderArgs
from autocoder.common.v2.agent.agentic_edit_tools.extra_docs import (
    _skill,
    _workflow_subagents,
    _plan_format,
    _interactive_session,
    _web_research,
    _ac_mod_files,
)
import typing

if typing.TYPE_CHECKING:
    from autocoder.common.v2.agent.agentic_edit import AgenticEdit


class LoadExtraDocumentToolResolver(BaseToolResolver):
    """加载内置额外文档（以 prompt 字符串形式返回）

    当前支持的文档：
    - workflow_subagents: Subagent Workflow YAML 规范与指导
    - skill: Skill 规范，教 AI 如何完成特定任务的说明书
    - plan_format: Plan 文件规范，教 AI 如何编写 .plan.md 项目计划文档
    - interactive_session: 交互式命令行会话的详细使用指南
    - web_research: 网页搜索与爬取的迭代式多轮研究方法论
    - ac_mod_files: AC 模块 (.ac.mod.md) 的完整使用与编写指南
    """

    def __init__(
        self,
        agent: Optional["AgenticEdit"],
        tool: LoadExtraDocumentTool,
        args: AutoCoderArgs,
    ):
        super().__init__(agent, tool, args)
        self.tool: LoadExtraDocumentTool = tool

    def _read_text_file(self, path: Path) -> str:
        try:
            return path.read_text(encoding="utf-8")
        except FileNotFoundError:
            raise FileNotFoundError(f"Document not found: {path}")

    def _render_plans_path(self, text: str) -> str:
        """Replace ~/.auto-coder/plans with the actual absolute path."""
        plans_dir = Path.home() / ".auto-coder" / "plans"
        actual_path = str(plans_dir)
        return text.replace("~/.auto-coder/plans", actual_path)

    def resolve(self) -> ToolResult:
        try:
            name = self.tool.name.strip()
            # 按名称选择对应的 prompt 函数，并返回其 prompt 文本（非模型推理输出）
            if name == "workflow_subagents":
                prompt_text = _workflow_subagents.prompt()
            elif name == "skill":
                prompt_text = _skill.prompt()
            elif name == "plan_format":
                prompt_text = _plan_format.prompt()
                # Render the actual plans directory path
                prompt_text = self._render_plans_path(prompt_text)
            elif name == "interactive_session":
                prompt_text = _interactive_session.prompt()
            elif name == "web_research":
                prompt_text = _web_research.prompt()
            elif name == "ac_mod_files":
                prompt_text = _ac_mod_files.prompt()
            else:
                # 正常不会进入此分支，_get_doc_text_by_name 已抛错
                raise ValueError(f"Unsupported document name: {name}")

            return ToolResult(
                success=True,
                message=f"Loaded extra document: {name}",
                content=prompt_text,
            )
        except Exception as e:
            return ToolResult(
                success=False,
                message=f"LoadExtraDocument failed: {str(e)}",
                content=None,
            )
