import inspect
import os
from typing import List, Dict, Any
import jinja2
from botrun_flow_lang.langgraph_agents.agents.langgraph_react_agent import (
    get_weather,
    multiply,
    add,
    divide,
    search,
    scrape,
    current_time,
    days_between,
    chat_with_pdf,
    chat_with_imgs,
    generate_tmp_public_url,
    web_search,
    generate_image,
    create_plotly_chart,
    create_mermaid_diagram,
)

# 工具函數列表
TOOLS = [
    get_weather,
    multiply,
    add,
    divide,
    search,
    scrape,
    current_time,
    days_between,
    chat_with_pdf,
    chat_with_imgs,
    generate_tmp_public_url,
    web_search,
    generate_image,
    create_plotly_chart,
    create_mermaid_diagram,
]


def get_tool_info(func) -> Dict[str, Any]:
    """獲取工具函數的文檔信息"""
    doc = inspect.getdoc(func)
    signature = inspect.signature(func)

    return {
        "name": func.__name__,
        "doc": doc,
        "parameters": [
            {
                "name": name,
                "annotation": (
                    param.annotation.__name__
                    if hasattr(param.annotation, "__name__")
                    else str(param.annotation)
                ),
                "default": (
                    param.default if param.default != inspect.Parameter.empty else None
                ),
            }
            for name, param in signature.parameters.items()
        ],
        "return_annotation": (
            signature.return_annotation.__name__
            if hasattr(signature.return_annotation, "__name__")
            else str(signature.return_annotation)
        ),
    }


def generate_html_docs():
    """生成HTML文檔"""
    # 獲取所有工具的信息
    tools_info = [get_tool_info(tool) for tool in TOOLS]

    # 讀取模板
    template_dir = os.path.join(os.path.dirname(__file__), "templates")
    template_loader = jinja2.FileSystemLoader(searchpath=template_dir)
    template_env = jinja2.Environment(loader=template_loader)
    template = template_env.get_template("tools.html")

    # 渲染HTML
    html_content = template.render(tools=tools_info)

    # 確保輸出目錄存在
    output_dir = os.path.join(
        os.path.dirname(os.path.dirname(__file__)), "static/docs/tools"
    )
    os.makedirs(output_dir, exist_ok=True)

    # 寫入HTML文件
    output_path = os.path.join(output_dir, "index.html")
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(html_content)

    print(f"文檔已生成到: {output_path}")


if __name__ == "__main__":
    generate_html_docs()
