// 1. 脚本部分:获取数据并传递
const responseData = pm.response.json();
const messages = responseData.data || [];

// 2. HTML 模板
const template = `
    <div id="status-bar" style="font-size:12px; color:#666; padding:10px; background:#fff; border-bottom:1px solid #eee;">
        状态: <span id="status-text">正在检查环境...</span>
    </div>
    <div id="chat-container"></div>

    <style>
        body { background: #f4f7f9; margin: 0; font-family: -apple-system, sans-serif; }
        #chat-container { max-width: 800px; margin: 20px auto; padding: 0 20px; display: flex; flex-direction: column; gap: 16px; }
        
        .msg-row { display: flex; width: 100%; }
        .row-user { flex-direction: row-reverse; }
        .avatar { width: 32px; height: 32px; border-radius: 8px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: bold; color: white; margin: 0 12px; }
        .row-user .avatar { background: #1677ff; }
        .row-ai .avatar { background: #10a37f; }

        .bubble { max-width: 80%; padding: 10px 16px; border-radius: 12px; font-size: 14px; line-height: 1.6; background: white; border: 1px solid #e8e8e8; }
        .row-user .bubble { background: #1677ff; color: white; border: none; }

        .status-call { text-align: center; font-size: 12px; color: #888; margin: 5px 0; }
        .status-call code { background: #e6e6e6; padding: 2px 4px; border-radius: 4px; }

        .tool-card { background: #fff; border: 1px solid #d9d9d9; border-radius: 8px; }
        details { padding: 10px; }
        summary { cursor: pointer; font-size: 13px; color: #555; display: flex; align-items: center; }
        .code-box { margin-top: 10px; background: #272822; border-radius: 4px; padding: 10px; overflow-x: auto; }
        pre { margin: 0; color: #f8f8f2; font-size: 12px; white-space: pre-wrap; font-family: monospace; }

        /* Markdown 内部样式 */
        .bubble table { border-collapse: collapse; width: 100%; margin: 8px 0; }
        .bubble th, .bubble td { border: 1px solid #ddd; padding: 6px; font-size: 12px; }
        .bubble p { margin: 8px 0; }
    </style>

    <script>
        // 动态加载脚本的函数
        function loadScript(url, callback) {
            const script = document.createElement('script');
            script.src = url;
            script.onload = callback;
            script.onerror = () => {
                document.getElementById('status-text').innerText = "加载失败: " + url;
                document.getElementById('status-text').style.color = "red";
            };
            document.head.appendChild(script);
        }

        // 备用 CDN 列表
        const cdns = [
            "https://cdn.jsdelivr.net/npm/markdown-it@13.0.1/dist/markdown-it.min.js",
            "https://unpkg.com/markdown-it@13.0.1/dist/markdown-it.min.js"
        ];

        let currentCdnIndex = 0;

        function initMarkdown() {
            loadScript(cdns[currentCdnIndex], () => {
                if (window.markdownit) {
                    document.getElementById('status-bar').style.display = 'none';
                    startRender();
                } else {
                    currentCdnIndex++;
                    if(currentCdnIndex < cdns.length) initMarkdown();
                }
            });
        }

        function startRender() {
            // 使用 pm.getData 获取 Apifox 传入的数据
            pm.getData((error, data) => {
                const messages = data.messages || [];
                const container = document.getElementById('chat-container');
                const md = window.markdownit({ html: true, linkify: true });

                messages.forEach(msg => {
                    const div = document.createElement('div');
                    
                    if (msg.messageType === 'tool_call') {
                        div.className = 'status-call';
                        div.innerHTML = '⚙️ 正在调用: <code>' + msg.toolName + '</code>';
                    } 
                    else if (msg.messageType === 'tool_result') {
                        div.className = 'tool-card';
                        let args = msg.toolArguments;
                        try { if(typeof args === 'string') args = JSON.stringify(JSON.parse(args), null, 2); } catch(e) {}
                        div.innerHTML = \`<details><summary>✅ 工具输出: <b>\${msg.toolName}</b></summary><div class="code-box"><pre><code>\${args}</code></pre></div></details>\`;
                    } 
                    else {
                        const isUser = msg.role === 'user';
                        div.className = 'msg-row ' + (isUser ? 'row-user' : 'row-ai');
                        const content = isUser ? msg.content : md.render(msg.content || '');
                        div.innerHTML = \`
                            <div class="avatar">\${isUser ? 'U' : 'AI'}</div>
                            <div class="bubble">\${content}</div>\`;
                    }
                    container.appendChild(div);
                });
            });
        }

        initMarkdown();
    </script>
`;

// 3. 设置可视化
pm.visualizer.set(template, { messages: messages });