import { assertReady, getEncodedProjectAndDays, loadProjectOptions, requestJson, saveSettings } from '../api.js';
import { escapeHtml, formatNumber } from '../render.js';
import { state } from '../state.js';

function labelConfigValue(groupKey, value) {
  const labels = {
    fileParserProviders: {
      local: '本地解析',
      'mineru-accurate-api': 'MinerU 精准解析 API',
      'mineru-agent-api': 'MinerU-Agent 轻量解析 API',
    },
    realTimeRender: { true: '开启', false: '关闭' },
    imageProviders: { volcengine: '火山方舟', 'google-ai-studio': 'Google AI Studio' },
    imageModelStatuses: { untested: '未测试', available: '可用', unavailable: '不可用' },
    bidAnalysisModes: { key: '只解析关键项', full: '完整解析' },
    outlineModes: { free: '自由生成', aligned: '按评分项对齐' },
    tableRequirements: { none: '不要', light: '少量', moderate: '适中', heavy: '大量' },
    useMermaidImages: { true: '开启', false: '关闭' },
    useAiImages: { true: '开启', false: '关闭' },
  };

  return labels[groupKey]?.[value] || value || '-';
}

function renderConfigUsage(usage) {
  const groups = [
    ['fileParserProviders', '文件解析方式'],
    ['realTimeRender', '实时渲染'],
    ['imageProviders', '生图服务商'],
    ['imageModelStatuses', '生图模型状态'],
    ['textModelNames', '文本模型请求'],
    ['imageModelNames', '生图模型请求'],
    ['bidAnalysisModes', 'Step 02 解析模式'],
    ['outlineModes', 'Step 03 目录模式'],
    ['tableRequirements', '正文表格需求'],
    ['useMermaidImages', 'Mermaid 图片'],
    ['useAiImages', 'AI 生图'],
  ];

  state.configUsage.innerHTML = `<div class="usage-grid">${groups.map(([key, label]) => {
    const rows = usage?.[key] || [];
    const body = rows.length
      ? `<table><thead><tr><th>取值</th><th>客户端</th><th>次数</th></tr></thead><tbody>${rows.map((row) => `
          <tr>
            <td><code>${escapeHtml(labelConfigValue(key, row.value))}</code></td>
            <td>${formatNumber(row.clients)}</td>
            <td>${formatNumber(row.events)}</td>
          </tr>
        `).join('')}</tbody></table>`
      : '<div class="empty">暂无数据</div>';
    return `<div class="usage-card"><h3>${escapeHtml(label)}</h3>${body}</div>`;
  }).join('')}</div>`;
}

export async function loadConfigUsage() {
  assertReady();
  await loadProjectOptions();
  saveSettings();

  const { projectName, days } = getEncodedProjectAndDays();
  const data = await requestJson(`/api/config-usage?projectName=${projectName}&days=${days}`);
  renderConfigUsage(data.usage || {});
}
