// 工具增强显示的渲染函数

export function escapeHtml(text: string): string {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

export function formatBytes(bytes: number): string {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
}

function formatToolStatusLabel(result: any, successLabel: string, failedLabel = '✗ 失败'): string {
  const state = String(result?.status || '').toLowerCase();
  if (state === 'awaiting_approval' || state === 'pending_approval' || state === 'pending') {
    return '待审批';
  }
  if (state === 'rejected') {
    return '✗ 已拒绝';
  }
  if (state === 'cancelled') {
    return '✗ 已取消';
  }
  return result?.success ? successLabel : failedLabel;
}

export function renderEnhancedToolResult(
  action: any,
  formatSearchTopic: (filters: Record<string, any>) => string,
  formatSearchTime: (filters: Record<string, any>) => string,
  formatSearchDomains: (filters: Record<string, any>) => string
): string {
  const tool = action.tool;
  const result = tool?.result;
  const args = tool?.arguments || {};
  const name = tool?.name;

  if (!result) {
    return '';
  }

  // 网络检索类
  if (name === 'web_search') {
    return renderWebSearch(result, args, formatSearchTopic, formatSearchTime, formatSearchDomains);
  } else if (name === 'extract_webpage') {
    return renderExtractWebpage(result, args);
  } else if (name === 'save_webpage') {
    return renderSaveWebpage(result, args);
  }

  // 文件编辑类
  else if (name === 'create_file' || name === 'create_folder') {
    return renderCreateFile(result, args);
  } else if (name === 'write_file') {
    return renderWriteFile(result, args);
  } else if (name === 'edit_file') {
    return renderEditFile(result, args);
  } else if (name === 'delete_file') {
    return renderDeleteFile(result, args);
  } else if (name === 'rename_file') {
    return renderRenameFile(result, args);
  }

  // 阅读聚焦类
  else if (name === 'read_file' || name === 'read_skill') {
    return renderReadFile(result, args);
  } else if (name === 'vlm_analyze') {
    return renderVlmAnalyze(result, args);
  } else if (name === 'ocr_image') {
    return renderOcrImage(result, args);
  } else if (name === 'view_image') {
    return renderViewImage(result, args);
  }

  // 终端类
  else if (name === 'terminal_session') {
    return renderTerminalSession(result, args);
  } else if (name === 'terminal_input') {
    return renderTerminalInput(result, args);
  } else if (name === 'terminal_snapshot') {
    return renderTerminalSnapshot(result, args);
  } else if (name === 'sleep') {
    return renderSleep(result, args);
  }

  // 终端指令类
  else if (name === 'run_command') {
    return renderRunCommand(result, args);
  } else if (name === 'run_python') {
    return renderRunPython(result, args);
  }

  // 记忆类
  else if (name === 'update_memory') {
    return renderUpdateMemory(result, args);
  }
  // 个性化管理类
  else if (name === 'manage_personalization') {
    return renderManagePersonalization(result, args);
  }

  // 待办事项类
  else if (name === 'todo_create') {
    return renderTodoCreate(result, args);
  } else if (name === 'todo_update_task') {
    return renderTodoUpdate(result);
  }

  // 彩蛋类
  else if (name === 'trigger_easter_egg') {
    return renderEasterEgg(result, args);
  }

  return '';
}

// 网络检索类渲染函数
function renderWebSearch(
  result: any,
  args: any,
  formatSearchTopic: (filters: Record<string, any>) => string,
  formatSearchTime: (filters: Record<string, any>) => string,
  formatSearchDomains: (filters: Record<string, any>) => string
): string {
  const query = result.query || args.query || '';
  const filters = result.filters || {};
  const totalResults = result.total_results || 0;
  const results = result.results || [];

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>搜索内容：</strong>${escapeHtml(query)}</div>`;
  html += `<div><strong>主题：</strong>${escapeHtml(formatSearchTopic(filters))}</div>`;
  html += `<div><strong>时间范围：</strong>${escapeHtml(formatSearchTime(filters))}</div>`;
  html += `<div><strong>限定网站：</strong>${escapeHtml(formatSearchDomains(filters))}</div>`;
  html += `<div><strong>结果数量：</strong>${totalResults}</div>`;
  html += '</div>';

  if (results.length > 0) {
    html += '<div class="search-result-list">';
    results.forEach((item: any) => {
      html += '<div class="search-result-item">';
      html += `<div class="search-result-title">${escapeHtml(item.title || '无标题')}</div>`;
      html += '<div class="search-result-url">';
      if (item.url) {
        html += `<a href="${escapeHtml(item.url)}" target="_blank">${escapeHtml(item.url)}</a>`;
      } else {
        html += '<span>无可用链接</span>';
      }
      html += '</div></div>';
    });
    html += '</div>';
  } else {
    html += '<div class="tool-result-empty">未返回详细的搜索结果。</div>';
  }

  return html;
}

function renderExtractWebpage(result: any, args: any): string {
  const url = args.url || result.url || '';
  const status = formatToolStatusLabel(result, '✓ 成功');
  const content = result.content || result.text || '';

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>URL：</strong>${escapeHtml(url)}</div>`;
  html += `<div><strong>状态：</strong>${status}</div>`;
  html += '</div>';

  if (content) {
    html += '<div class="tool-result-content scrollable">';
    html += `<pre>${escapeHtml(content)}</pre>`;
    html += '</div>';
  }

  return html;
}

function renderSaveWebpage(result: any, args: any): string {
  const url = args.url || result.url || '';
  const path = result.path || args.save_path || '';
  const status = formatToolStatusLabel(result, '✓ 已保存');

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>URL：</strong>${escapeHtml(url)}</div>`;
  html += `<div><strong>保存路径：</strong>${escapeHtml(path)}</div>`;
  html += `<div><strong>状态：</strong>${status}</div>`;
  html += '</div>';

  return html;
}

// 文件编辑类渲染函数
function renderCreateFile(result: any, args: any): string {
  const path = args.path || result.path || '';
  const status = formatToolStatusLabel(result, '✓ 已创建');

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>路径：</strong>${escapeHtml(path)}</div>`;
  html += `<div><strong>状态：</strong>${status}</div>`;
  html += '</div>';

  return html;
}

function renderWriteFile(result: any, args: any): string {
  const path = args.file_path || args.path || result.path || '';
  const status = formatToolStatusLabel(result, '✓ 已写入');
  const content = args.content || '';
  const appendFlag = typeof args.append === 'boolean' ? args.append : null;
  const modeRaw = String(result.mode || '').toLowerCase();
  const writeMode =
    appendFlag === true || modeRaw === 'a'
      ? '追加'
      : appendFlag === false || modeRaw === 'w'
        ? '覆盖'
        : '无';

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>路径：</strong>${escapeHtml(path)}</div>`;
  html += `<div><strong>状态：</strong>${status}</div>`;
  html += `<div><strong>模式：</strong>${writeMode}</div>`;
  if (!result.success && result.error) {
    html += `<div><strong>错误：</strong>${escapeHtml(String(result.error))}</div>`;
  }
  html += '</div>';

  // 显示写入的内容
  if (result.success && content) {
    html += '<div class="tool-result-diff scrollable">';
    const lines = content.split('\n');
    lines.forEach((line: string) => {
      html += `<div class="diff-line diff-add">+ ${escapeHtml(line)}</div>`;
    });
    html += '</div>';
  }

  return html;
}

function renderEditFile(result: any, args: any): string {
  const path = args.file_path || args.path || result.path || '';
  const status = formatToolStatusLabel(result, '✓ 已编辑');
  const replaceAllValue =
    typeof args.replace_all === 'boolean' ? (args.replace_all ? '开' : '关') : '无';
  const foundCount =
    typeof result.found_matches === 'number'
      ? result.found_matches
      : typeof result.replacements === 'number'
        ? result.replacements
        : null;
  const replacedCount = typeof result.replacements === 'number' ? result.replacements : null;

  // 兼容两种数据格式：
  // 1. 新格式：args.replacements 数组
  // 2. 旧格式：args.old_string 和 args.new_string
  const replacements = args.replacements || [];
  let oldString = args.old_string || '';
  let newString = args.new_string || '';

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>路径：</strong>${escapeHtml(path)}</div>`;
  html += `<div><strong>状态：</strong>${status}</div>`;
  html += `<div><strong>替换全部：</strong>${replaceAllValue}</div>`;
  html += `<div><strong>找到：</strong>${foundCount ?? '无'}处</div>`;
  html += `<div><strong>替换：</strong>${replacedCount ?? '无'}处</div>`;
  if (!result.success && result.error) {
    html += `<div><strong>错误：</strong>${escapeHtml(String(result.error))}</div>`;
  }
  html += '</div>';

  if (!result.success) {
    return html;
  }

  // 如果有 replacements 数组，使用新格式
  if (replacements.length > 0) {
    html += '<div class="tool-result-diff scrollable">';
    replacements.forEach((rep: any, idx: number) => {
      if (idx > 0) html += '<div class="diff-separator">⋮</div>';

      const oldText = rep.old_text || rep.old || '';
      const newText = rep.new_text || rep.new || '';

      if (oldText) {
        const oldLines = oldText.split('\n');
        oldLines.forEach((line: string) => {
          html += `<div class="diff-line diff-remove">- ${escapeHtml(line)}</div>`;
        });
      }

      if (newText) {
        const newLines = newText.split('\n');
        newLines.forEach((line: string) => {
          html += `<div class="diff-line diff-add">+ ${escapeHtml(line)}</div>`;
        });
      }
    });
    html += '</div>';
  }
  // 否则使用旧格式（old_string/new_string）
  else if (oldString || newString) {
    // 处理转义的 \n
    oldString = oldString.replace(/\\n/g, '\n');
    newString = newString.replace(/\\n/g, '\n');

    html += '<div class="tool-result-diff scrollable">';

    if (oldString) {
      const oldLines = oldString.split('\n');
      oldLines.forEach((line: string) => {
        html += `<div class="diff-line diff-remove">- ${escapeHtml(line)}</div>`;
      });
    }

    if (newString) {
      const newLines = newString.split('\n');
      newLines.forEach((line: string) => {
        html += `<div class="diff-line diff-add">+ ${escapeHtml(line)}</div>`;
      });
    }

    html += '</div>';
  }

  return html;
}

function renderDeleteFile(result: any, args: any): string {
  const path = args.path || result.path || '';
  const status = formatToolStatusLabel(result, '✓ 已删除');

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>路径：</strong>${escapeHtml(path)}</div>`;
  html += `<div><strong>状态：</strong>${status}</div>`;
  html += '</div>';

  return html;
}

function renderRenameFile(result: any, args: any): string {
  const oldPath = args.old_path || args.source || result.old_path || '';
  const newPath = args.new_path || args.destination || result.new_path || '';
  const status = formatToolStatusLabel(result, '✓ 已重命名');

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>路径：</strong>${escapeHtml(oldPath)}</div>`;
  html += `<div><strong>状态：</strong>${status}</div>`;
  html += `<div><strong>重命名：</strong>${escapeHtml(oldPath)} → ${escapeHtml(newPath)}</div>`;
  html += '</div>';

  return html;
}

// 阅读聚焦类渲染函数
function renderReadFile(result: any, args: any): string {
  const path = args.path || result.path || '';
  const status = formatToolStatusLabel(result, '✓ 成功');
  const size = result.size || result.file_size || 0;
  const readType = result.type || 'read';

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>路径：</strong>${escapeHtml(path)}</div>`;
  html += `<div><strong>状态：</strong>${status}</div>`;
  if (size > 0) {
    html += `<div><strong>大小：</strong>${formatBytes(size)}</div>`;
  }
  if (readType !== 'read') {
    html += `<div><strong>模式：</strong>${escapeHtml(readType)}</div>`;
  }
  html += '</div>';

  // 处理普通读取模式
  if (readType === 'read') {
    const content = result.content || result.text || '';
    if (content) {
      html += '<div class="tool-result-content scrollable">';
      html += `<pre>${escapeHtml(content)}</pre>`;
      html += '</div>';
    }
  }
  // 处理搜索模式
  else if (readType === 'search') {
    const matches = result.matches || [];
    const query = result.query || args.query || '';

    if (query) {
      html += '<div class="tool-result-meta">';
      html += `<div><strong>搜索关键词：</strong>${escapeHtml(query)}</div>`;
      html += `<div><strong>匹配数量：</strong>${matches.length}</div>`;
      html += '</div>';
    }

    if (matches.length > 0) {
      html += '<div class="tool-result-content scrollable">';
      matches.forEach((match: any, idx: number) => {
        if (idx > 0) html += '<div class="search-match-separator">⋯</div>';
        html += '<div class="search-match-item">';
        html += `<div class="search-match-line">行 ${match.line_number || '?'}</div>`;
        html += `<pre>${escapeHtml(match.snippet || match.content || '')}</pre>`;
        html += '</div>';
      });
      html += '</div>';
    } else {
      html += '<div class="tool-result-empty">未找到匹配内容</div>';
    }
  }
  // 处理提取模式
  else if (readType === 'extract') {
    const segments = result.segments || [];

    if (segments.length > 0) {
      html += '<div class="tool-result-meta">';
      html += `<div><strong>提取片段数：</strong>${segments.length}</div>`;
      html += '</div>';

      html += '<div class="tool-result-content scrollable">';
      segments.forEach((segment: any, idx: number) => {
        if (idx > 0) html += '<div class="segment-separator">⋯</div>';
        html += '<div class="segment-item">';
        const startLine = segment.start_line || segment.line_start || '?';
        const endLine = segment.end_line || segment.line_end || '?';
        html += `<div class="segment-range">行 ${startLine}-${endLine}</div>`;
        html += `<pre>${escapeHtml(segment.content || segment.text || '')}</pre>`;
        html += '</div>';
      });
      html += '</div>';
    } else {
      html += '<div class="tool-result-empty">未提取到内容</div>';
    }
  }

  return html;
}

function renderVlmAnalyze(result: any, args: any): string {
  const path = args.image_path || args.path || result.path || '';
  const status = formatToolStatusLabel(result, '✓ 成功');
  const analysis = result.analysis || result.result || '';

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>路径：</strong>${escapeHtml(path)}</div>`;
  html += `<div><strong>状态：</strong>${status}</div>`;
  html += '</div>';

  if (analysis) {
    html += '<div class="tool-result-content scrollable">';
    html += '<div class="content-label">分析结果：</div>';
    html += `<pre>${escapeHtml(analysis)}</pre>`;
    html += '</div>';
  }

  return html;
}

function renderOcrImage(result: any, args: any): string {
  const path = args.image_path || args.path || result.path || '';
  const status = formatToolStatusLabel(result, '✓ 成功');
  const size = result.size || result.file_size || 0;
  const text = result.text || result.ocr_text || '';
  const imageUrl = result.image_url || result.url || '';

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>路径：</strong>${escapeHtml(path)}</div>`;
  html += `<div><strong>状态：</strong>${status}</div>`;
  if (size > 0) {
    html += `<div><strong>大小：</strong>${formatBytes(size)}</div>`;
  }
  html += '</div>';

  if (imageUrl) {
    html += `<div class="tool-result-image"><img src="${escapeHtml(imageUrl)}" alt="OCR图片" style="max-width: 100%; height: auto;" /></div>`;
  }

  if (text) {
    html += '<div class="tool-result-content scrollable">';
    html += '<div class="content-label">识别文本：</div>';
    html += `<pre>${escapeHtml(text)}</pre>`;
    html += '</div>';
  }

  return html;
}

function renderViewImage(result: any, args: any): string {
  const path = args.image_path || args.path || result.path || '';
  const status = formatToolStatusLabel(result, '✓ 成功');
  const size = result.size || result.file_size || 0;
  const imageUrl = result.image_url || result.url || '';

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>路径：</strong>${escapeHtml(path)}</div>`;
  html += `<div><strong>状态：</strong>${status}</div>`;
  if (size > 0) {
    html += `<div><strong>大小：</strong>${formatBytes(size)}</div>`;
  }
  html += '</div>';

  if (imageUrl) {
    html += `<div class="tool-result-image"><img src="${escapeHtml(imageUrl)}" alt="查看图片" style="max-width: 100%; height: auto;" /></div>`;
  }

  return html;
}

// 终端类渲染函数
function renderTerminalSession(result: any, args: any): string {
  const operation = args.operation || args.action || 'start';
  const sessionName = args.session_name || args.name || result.session_name || '';
  const status = formatToolStatusLabel(result, '✓ 成功');

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>操作：</strong>${escapeHtml(operation)}</div>`;
  html += `<div><strong>终端名：</strong>${escapeHtml(sessionName)}</div>`;
  html += `<div><strong>状态：</strong>${status}</div>`;
  html += '</div>';

  return html;
}

function renderTerminalInput(result: any, args: any): string {
  const command = args.command || args.input || '';
  const timeout = args.timeout || 30;
  const output = result.output || result.result || '';

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>指令：</strong>${escapeHtml(command)}</div>`;
  html += `<div><strong>超时时间：</strong>${timeout}秒</div>`;
  html += '</div>';

  if (output) {
    html += '<div class="tool-result-content scrollable">';
    html += '<div class="content-label">输出：</div>';
    html += `<pre>${escapeHtml(output)}</pre>`;
    html += '</div>';
  }

  return html;
}

function renderTerminalSnapshot(result: any, args: any): string {
  const sessionName = args.session_name || args.name || result.session_name || '';
  const status = formatToolStatusLabel(result, '✓ 成功');
  const startLine = args.start_line || 0;
  const endLine = args.end_line || 0;
  const content = result.content || result.output || '';

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>状态：</strong>${status}</div>`;
  html += `<div><strong>终端名：</strong>${escapeHtml(sessionName)}</div>`;
  if (startLine || endLine) {
    html += `<div><strong>行范围：</strong>${startLine} - ${endLine}</div>`;
  }
  html += '</div>';

  if (content) {
    html += '<div class="tool-result-content scrollable">';
    html += '<div class="content-label">获取的内容：</div>';
    html += `<pre>${escapeHtml(content)}</pre>`;
    html += '</div>';
  }

  return html;
}

function renderSleep(result: any, args: any): string {
  const seconds = args.seconds || args.duration || 0;
  const status = formatToolStatusLabel(result, '✓ 完成');

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>等待时间：</strong>${seconds}秒</div>`;
  html += `<div><strong>状态：</strong>${status}</div>`;
  html += '</div>';

  return html;
}

// 终端指令类渲染函数
function renderRunCommand(result: any, args: any): string {
  const command = args.command || '';
  const timeout = args.timeout || 30;
  const output = result.output || result.stdout || '';
  const exitCode = result.exit_code !== undefined ? result.exit_code : result.returncode;

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>指令：</strong>${escapeHtml(command)}</div>`;
  html += `<div><strong>超时时间：</strong>${timeout}秒</div>`;
  if (exitCode !== undefined) {
    html += `<div><strong>退出码：</strong>${exitCode}</div>`;
  }
  html += '</div>';

  if (output) {
    html += '<div class="tool-result-content scrollable">';
    html += '<div class="content-label">输出：</div>';
    html += `<pre>${escapeHtml(output)}</pre>`;
    html += '</div>';
  }

  return html;
}

function renderRunPython(result: any, args: any): string {
  const code = result.code || args.code || '';
  const output = result.output || '';

  let html = '<div class="code-block">';
  html += '<div class="code-label">代码：</div>';
  html += `<pre><code class="language-python">${escapeHtml(code)}</code></pre>`;
  html += '</div>';

  if (output) {
    html += '<div class="output-block">';
    html += '<div class="output-label">输出：</div>';
    html += `<pre>${escapeHtml(output)}</pre>`;
    html += '</div>';
  }

  return html;
}

// 记忆类渲染函数
function renderUpdateMemory(result: any, args: any): string {
  const operation = args.operation || result.operation || '';
  const content = args.content || '';
  const index = args.index || result.index;
  const count = result.count || 0;

  let html = '<div class="tool-result-meta">';

  if (operation === 'append') {
    html += `<div>新增记忆</div>`;
    html += `<div>${count}. ${escapeHtml(content)}</div>`;
  } else if (operation === 'replace') {
    html += `<div>更新记忆</div>`;
    html += `<div>${index}. ${escapeHtml(content)}</div>`;
  } else if (operation === 'delete') {
    html += `<div>删除记忆</div>`;
    html += `<div>${index}. ${escapeHtml(content || '已删除')}</div>`;
  }

  html += '</div>';

  return html;
}

function formatPersonalizationFieldLabel(field: string): string {
  const labelMap: Record<string, string> = {
    self_identify: 'AI 自称',
    user_name: '用户称呼',
    profession: '用户职业',
    tone: '交流语气',
    considerations: '注意事项',
    theme: '主题',
    communication_style: '交流风格',
    enabled: '个性化开关'
  };
  return labelMap[field] || field;
}

function formatPersonalizationFieldValue(field: string, value: any): string {
  if (value === null || value === undefined || value === '') {
    return '未设置';
  }
  if (field === 'enabled') {
    return value ? '开启' : '关闭';
  }
  if (field === 'considerations') {
    if (!Array.isArray(value) || value.length === 0) {
      return '未设置';
    }
    return value.map((item) => String(item)).join('、');
  }
  return String(value);
}

function renderManagePersonalization(result: any, args: any): string {
  const action = String(args.action || result.action || 'read');
  const status = formatToolStatusLabel(result, action === 'update' ? '✓ 已更新' : '✓ 已读取');
  const field = String(result.updated_field || args.field || '');
  const newValue = result.updated_value ?? args.value;

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>操作：</strong>${escapeHtml(action === 'update' ? '更新配置' : '读取配置')}</div>`;
  html += `<div><strong>状态：</strong>${status}</div>`;

  if (!result?.success) {
    if (result?.error) {
      html += `<div><strong>错误：</strong>${escapeHtml(String(result.error))}</div>`;
    }
    if (Array.isArray(result?.validation_errors) && result.validation_errors.length > 0) {
      html += `<div><strong>校验：</strong>${escapeHtml(result.validation_errors.join('；'))}</div>`;
    }
    html += '</div>';
    return html;
  }

  if (action === 'update' && field) {
    html += `<div><strong>修改项：</strong>${escapeHtml(formatPersonalizationFieldLabel(field))}</div>`;
    html += `<div><strong>修改后：</strong>${escapeHtml(formatPersonalizationFieldValue(field, newValue))}</div>`;
  }

  html += '</div>';
  return html;
}

// 待办事项类渲染函数
function renderTodoCreate(result: any, args: any): string {
  const status = formatToolStatusLabel(result, '✓ 已创建');
  const todoList = result.todo_list || {};
  const title = todoList.title || args.title || '';
  const tasks = todoList.tasks || args.tasks || [];

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>状态：</strong>${status}</div>`;
  html += `<div><strong>标题：</strong>${escapeHtml(title)}</div>`;
  html += '</div>';

  if (tasks.length > 0) {
    html += '<div class="tool-result-content">';
    html += '<div class="todo-list">';
    tasks.forEach((task: any) => {
      const taskText =
        typeof task === 'string' ? task : task.text || task.title || task.content || '';
      html += `<div class="todo-item"><input type="checkbox" disabled /> ${escapeHtml(taskText)}</div>`;
    });
    html += '</div>';
    html += '</div>';
  }

  return html;
}

function renderTodoUpdate(result: any): string {
  const status = formatToolStatusLabel(result, '✓ 已更新');
  const todoList = result.todo_list || {};
  const title = todoList.title || '';
  const tasks = todoList.tasks || [];

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>状态：</strong>${status}</div>`;
  html += `<div><strong>标题：</strong>${escapeHtml(title)}</div>`;
  html += '</div>';

  if (tasks.length > 0) {
    html += '<div class="tool-result-content">';
    html += '<div class="todo-list">';
    tasks.forEach((task: any) => {
      const taskText =
        typeof task === 'string' ? task : task.text || task.title || task.content || '';
      const completed =
        typeof task === 'object' &&
        (task.status === 'done' || task.completed || task.done || task.checked);
      html += `<div class="todo-item"><input type="checkbox" ${completed ? 'checked' : ''} disabled /> ${escapeHtml(taskText)}</div>`;
    });
    html += '</div>';
    html += '</div>';
  }

  return html;
}

// 彩蛋类渲染函数
function renderEasterEgg(result: any, args: any): string {
  const status = formatToolStatusLabel(result, '✓ 已触发');
  const type = result.type || args.type || '';
  const content = result.content || result.message || '';

  let html = '<div class="tool-result-meta">';
  html += `<div><strong>状态：</strong>${status}</div>`;
  html += `<div><strong>类型：</strong>${escapeHtml(type)}</div>`;
  html += '</div>';

  if (content) {
    html += '<div class="tool-result-content">';
    html += `<div class="easter-egg-content">${escapeHtml(content)}</div>`;
    html += '</div>';
  }

  return html;
}
