#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
templateHtml.py - 生成 Trace 执行流程可视化 HTML
参考 visualize.py 的样式设计
"""

import json
import os
from pathlib import Path


def generate_trace_visualization_html(goal_list: list, msg_groups: dict, output_path: str = None):
    """
    生成 Trace 可视化 HTML 文件

    Args:
        goal_list: 节点列表
        msg_groups: 节点消息分组
        output_path: 输出的 HTML 文件路径
    """
    if goal_list is None:
        goal_list = []
    if msg_groups is None:
        msg_groups = {}

    # 1.新建一个数组goal_list_new = goal_list
    goal_list_new = list(goal_list)

    # 2.查找msg_groups如果里面包含START，那么需要在goal_list_new添加一个对象
    if "START" in msg_groups:
        start_node = {
            "id": "START",
            "description": "START",
            "reason": None,
            "parent_id": None,
            "type": "start",
            "status": "completed",
            "summary": None,
            "sub_trace_ids": None,
            "agent_call_mode": None,
            "self_stats": None,
            "cumulative_stats": None,
            "created_at": None,
            "sub_trace_metadata": None
        }
        # 确保 START 节点在最前面或合适位置，这里直接 append
        # 如果需要它作为根节点被正确渲染，它应该在列表里即可
        goal_list_new.insert(0, start_node)

    # 读取 HTML 模板
    template_path = Path(__file__).parent / "trace_template.html"
    with open(template_path, "r", encoding="utf-8") as f:
        template_content = f.read()

    html_content = template_content.replace(
        '"__GOAL_LIST__"',
        json.dumps(goal_list_new, ensure_ascii=False)
    ).replace(
        '"__MSG_GROUPS__"',
        json.dumps(msg_groups, ensure_ascii=False)
    )

    # 确定输出路径
    if output_path is None:
        output_path = Path(__file__).parent / "trace_visualization.html"
    else:
        output_path = Path(output_path)


    mock_dir = Path(__file__).parent / "mock_data"
    mock_dir.mkdir(parents=True, exist_ok=True)
    with open(mock_dir / "goal_list.json", "w", encoding="utf-8") as f:
        json.dump(goal_list_new, f, ensure_ascii=False, indent=2)
    with open(mock_dir / "msg_groups.json", "w", encoding="utf-8") as f:
        json.dump(msg_groups, f, ensure_ascii=False, indent=2)
    # 写入 HTML 文件
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(html_content)

    print(f"可视化文件已生成: {output_path}")
    return output_path


if __name__ == "__main__":
    generate_trace_visualization_html([], {})
