import json
import os
import html

def create_html_report_v2(json_path, html_path):
    """
    (改进版)
    将指定的JSON文件转换为一个带有导航和三列图文布局的HTML报告。
    - 布局: 原始截图 | 标记截图 | 文本信息
    - 图片大小通过Flexbox比例控制，使其视觉上更小。
    """
    print(f"正在读取JSON文件: {json_path}")
    try:
        with open(json_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"错误: 无法读取或解析JSON文件。 {e}")
        return

    # --- HTML 模板和样式 ---
    html_template = """
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>任务执行报告</title>
        <style>
            body {{
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
                line-height: 1.6;
                margin: 0;
                padding: 0;
                background-color: #f4f7f9;
                color: #333;
            }}
            .container {{
                max-width: 1400px; /* 增加了最大宽度以适应三列布局 */
                margin: 20px auto;
                padding: 20px;
                background-color: #fff;
                box-shadow: 0 4px 8px rgba(0,0,0,0.1);
                border-radius: 8px;
            }}
            h1 {{
                text-align: center;
                color: #2c3e50;
                border-bottom: 2px solid #e0e0e0;
                padding-bottom: 10px;
            }}
            nav {{
                background-color: #ecf0f1;
                padding: 15px;
                border-radius: 5px;
                margin-bottom: 30px;
            }}
            nav h2 {{
                margin-top: 0;
                color: #34495e;
            }}
            nav ul {{
                list-style-type: none;
                padding: 0;
                margin: 0;
            }}
            nav li a {{
                text-decoration: none;
                color: #2980b9;
                font-weight: bold;
                display: block;
                padding: 8px 0;
                transition: color 0.3s;
            }}
            nav li a:hover {{
                color: #3498db;
            }}
            .goal-section {{
                margin-bottom: 40px;
                padding-top: 20px;
            }}
            .goal-title {{
                color: #16a085;
                border-bottom: 2px solid #1abc9c;
                padding-bottom: 5px;
            }}
            /* --- 关键CSS改动开始 --- */
            .step-container {{
                display: flex; /* 启用Flexbox布局 */
                gap: 20px; /* 设置列之间的间距 */
                margin-bottom: 25px;
                padding: 15px;
                border: 1px solid #ddd;
                border-radius: 5px;
                background-color: #fafafa;
                align-items: flex-start; /* 顶部对齐 */
            }}
            .image-column {{
                flex: 1; /* 每张图片列占1份空间 */
                min-width: 0; /* 防止图片在缩小flex容器时溢出 */
            }}
            .image-column img {{
                width: 100%; /* 图片宽度填充其列，实现响应式缩放 */
                height: auto;
                border: 1px solid #ccc;
                border-radius: 4px;
            }}
            .text-container {{
                flex: 2; /* 文本列占2份空间，使其比图片列更宽 */
            }}
            /* --- 关键CSS改动结束 --- */
            .text-container h4 {{
                margin-top: 0;
                color: #8e44ad;
            }}
            .text-container p, .text-container pre {{
                white-space: pre-wrap;
                word-wrap: break-word;
                background-color: #ecf0f1;
                padding: 10px;
                border-radius: 4px;
                font-size: 14px;
            }}
            .action-code {{
                font-family: "Courier New", Courier, monospace;
                color: #c0392b;
                font-weight: bold;
            }}
            .screenshot-label {{
                font-weight: bold;
                text-align: center;
                margin-bottom: 5px;
                color: #7f8c8d;
            }}
        </style>
    </head>
    <body>
        <div class="container">
            <h1>任务执行报告</h1>
            <nav id="navigation">
                <h2>导航</h2>
                <ul>
                    {navigation_links}
                </ul>
            </nav>
            <main id="content">
                {content_body}
            </main>
        </div>
    </body>
    </html>
    """

    # 生成导航链接
    nav_links = []
    for i, goal_item in enumerate(data):
        goal_title = html.escape(goal_item.get("GOAL", f"未命名目标 {i+1}"))
        nav_links.append(f'<li><a href="#goal-{i}">{i+1}. {goal_title}</a></li>')
    navigation_html = "\n".join(nav_links)

    # 生成主内容
    content_sections = []
    for i, goal_item in enumerate(data):
        goal_title = html.escape(goal_item.get("GOAL", f"未命名目标 {i+1}"))
        
        section_content = [f'<section id="goal-{i}" class="goal-section">']
        section_content.append(f'<h2 class="goal-title">目标 {i+1}: {goal_title}</h2>')
        
        steps = goal_item.get("steps", [])
        if not steps:
            section_content.append("<p>此目标下没有步骤。</p>")
        
        for j, step in enumerate(steps):
            original_img = step.get("original_screenshot", "")
            marked_img = step.get("marked_screenshot", "")
            thought = html.escape(step.get("ACTION THOUGHT", "N/A"))
            action = html.escape(step.get("ACTION", "N/A"))
            description = html.escape(step.get("ACTION DESCRIPTION", "N/A"))

            # --- 关键HTML结构改动 ---
            # 现在是三个并排的div，而不是之前的两列嵌套结构
            step_html = f"""
            <div class="step-container">
                <div class="image-column">
                    <p class="screenshot-label">原始截图 (Original)</p>
                    <img src="{original_img}" alt="原始截图" onerror="this.alt='图片加载失败'; this.src='';">
                </div>
                <div class="image-column">
                    <p class="screenshot-label">标记截图 (Marked)</p>
                    <img src="{marked_img}" alt="标记截图" onerror="this.alt='图片加载失败'; this.src='';">
                </div>
                <div class="text-container">
                    <h4>第 {j+1} 步: 思考 (Action Thought)</h4>
                    <p>{thought}</p>
                    <h4>动作 (Action)</h4>
                    <pre><code class="action-code">{action}</code></pre>
                    <h4>动作描述 (Action Description)</h4>
                    <p>{description}</p>
                </div>
            </div>
            """
            section_content.append(step_html)
        
        section_content.append('</section>')
        content_sections.append("\n".join(section_content))

    content_body_html = "\n".join(content_sections)

    # 组合并写入文件
    final_html = html_template.format(
        navigation_links=navigation_html,
        content_body=content_body_html
    )

    print(f"正在生成HTML报告: {html_path}")
    try:
        with open(html_path, 'w', encoding='utf-8') as f:
            f.write(final_html)
        print(f"\n✅ 报告生成成功！请在浏览器中打开: {os.path.abspath(html_path)}")
    except IOError as e:
        print(f"错误: 无法写入HTML文件。 {e}")

# --- 如何使用 ---
if __name__ == "__main__":
    input_json_file = "/Users/didi/Documents/mhz/GUI/mobile-use/output_state_transition_logic.json" 
    output_html_file = "all_router_click_recorrect.html"

    if not os.path.exists(input_json_file):
        print(f"警告: JSON文件 '{input_json_file}' 不存在。将创建一个示例文件用于测试。")
        sample_data = [
            {
                "GOAL": "Record an audio clip using Audio Recorder app and save it.",
                "steps": [
                    { "original_screenshot": "/path/to/nonexistent_image1.png", "marked_screenshot": "/path/to/nonexistent_image2.png", "ACTION THOUGHT": "[Corrected] The agent attempted to open the Audio Recorder app...", "ACTION": "click(coordinate=(420, 780))", "ACTION DESCRIPTION": "Tap on the Audio Recorder app icon to open it." },
                    { "original_screenshot": "/path/to/nonexistent_image3.png", "marked_screenshot": "/path/to/nonexistent_image4.png", "ACTION THOUGHT": "Since the audio has been recorded and saved successfully...", "ACTION": "terminate(status=success)", "ACTION DESCRIPTION": "Terminate the task as it has been successfully completed." }
                ]
            }
        ]
        with open(input_json_file, 'w', encoding='utf-8') as f:
            json.dump(sample_data, f, indent=4)

    create_html_report_v2(input_json_file, output_html_file)