// ---------- RAG push logs ----------
const RAGPUSH_STATE = { page: 1, pageSize: 20, q: "", source: "", status: "", rows: [], total: 0, summary: null };

PAGES.ragpush = async () => {
  const ws = document.getElementById("workspace");
  ws.innerHTML = `
    <div id="rp-summary"></div>
    <div class="card p-4">
      <div class="flex gap-2 flex-wrap items-center">
        <input id="rp-q" placeholder="按文章标题查询" class="border border-slate-200 rounded px-3 py-1.5 text-sm w-72"/>
        <select id="rp-source" class="border border-slate-200 rounded px-3 py-1.5 text-sm">
          <option value="">全部来源</option>
          <option value="manual">手动推送</option>
          <option value="auto">自动推送</option>
        </select>
        <select id="rp-status" class="border border-slate-200 rounded px-3 py-1.5 text-sm">
          <option value="">全部状态</option>
          <option value="running">推送中</option>
          <option value="completed">成功</option>
          <option value="failed">失败</option>
        </select>
        <button onclick="loadRagPushLogs()" class="bg-[#1D4ED8] hover:bg-blue-700 text-white text-sm rounded px-4 py-1.5">查询</button>
      </div>
    </div>
    <div id="rp-results"></div>`;
  document.getElementById("rp-q").value = RAGPUSH_STATE.q || "";
  document.getElementById("rp-source").value = RAGPUSH_STATE.source || "";
  document.getElementById("rp-status").value = RAGPUSH_STATE.status || "";
  ["rp-q", "rp-source", "rp-status"].forEach(id => {
    document.getElementById(id).addEventListener("keydown", e => {
      if (e.key === "Enter") loadRagPushLogs();
    });
  });
  loadRagPushLogs();
};

function _duration(ms) {
  if (ms == null) return "—";
  if (ms < 1000) return `${ms} ms`;
  const sec = ms / 1000;
  if (sec < 60) return `${sec.toFixed(1)} s`;
  return `${(sec / 60).toFixed(1)} min`;
}

function _ragPushStatusPill(status) {
  if (status === "completed") return pill("成功", "green");
  if (status === "failed") return pill("失败", "red");
  if (status === "running") return pill("推送中", "blue");
  return pill(status || "未知", "slate");
}

function _ragPushSourcePill(source) {
  return source === "auto" ? pill("自动", "blue") : pill("手动", "slate");
}

async function loadRagPushLogs({ resetPage = true } = {}) {
  if (resetPage) RAGPUSH_STATE.page = 1;
  RAGPUSH_STATE.q = document.getElementById("rp-q")?.value.trim() || "";
  RAGPUSH_STATE.source = document.getElementById("rp-source")?.value || "";
  RAGPUSH_STATE.status = document.getElementById("rp-status")?.value || "";
  const qs = new URLSearchParams();
  qs.set("limit", String(RAGPUSH_STATE.pageSize));
  qs.set("offset", String((RAGPUSH_STATE.page - 1) * RAGPUSH_STATE.pageSize));
  if (RAGPUSH_STATE.q) qs.set("q", RAGPUSH_STATE.q);
  if (RAGPUSH_STATE.source) qs.set("source", RAGPUSH_STATE.source);
  if (RAGPUSH_STATE.status) qs.set("status", RAGPUSH_STATE.status);
  const box = document.getElementById("rp-results");
  box.innerHTML = `<div class="text-slate-400 text-sm">加载中…</div>`;
  try {
    const r = await api("/api/rag-push-logs?" + qs);
    RAGPUSH_STATE.rows = r.items || [];
    RAGPUSH_STATE.total = r.total || 0;
    RAGPUSH_STATE.summary = r.summary || null;
    _renderRagPushSummary();
    _renderRagPushTable();
  } catch (e) {
    box.innerHTML = `<div class="card p-6 text-sm text-red-600">加载失败：${esc(e.message)}</div>`;
  }
}

function _renderRagPushSummary() {
  const s = RAGPUSH_STATE.summary || {};
  const server = s.rag_server || {};
  const cfg = s.auto_push || {};
  const serverText = server.host ? `${server.host}${server.port ? ":" + server.port : ""}` : "未配置";
  document.getElementById("rp-summary").innerHTML = `
    <div class="grid grid-cols-1 md:grid-cols-5 gap-3">
      ${statCard("推送数量", s.push_count ?? 0, "", "", "article_rag_push_log 总记录数")}
      ${statCard("失败数量", s.failed_count ?? 0, "", "", "status = failed")}
      ${statCard("平均耗时", _duration(s.avg_duration_ms), "", "", "按已结束记录统计")}
      ${statCard("RAG服务器", serverText, "", "", server.url || "RAG_INGEST_URL 未配置")}
      <div class="card p-[18px] flex flex-col gap-2.5">
        <div class="text-[13px] text-slate-500">拉取完成后自动推送</div>
        <label class="inline-flex items-center gap-2 text-sm">
          <input id="rp-auto-toggle" type="checkbox" ${cfg.enabled ? "checked" : ""}/>
          <span>${cfg.enabled ? "已开启" : "已关闭"}</span>
        </label>
        <div class="text-xs text-slate-400">env默认：${cfg.env_default ? "开启" : "关闭"}${cfg.overridden ? " · 当前运行时已覆盖" : ""}</div>
      </div>
    </div>`;
  const toggle = document.getElementById("rp-auto-toggle");
  if (toggle) {
    toggle.onchange = async () => {
      try {
        await api("/api/rag-push-logs/config", {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ enabled: toggle.checked }),
        });
        toast(toggle.checked ? "已开启自动推送" : "已关闭自动推送");
        await loadRagPushLogs({ resetPage: false });
      } catch (e) {
        toast(e.message, "err");
        toggle.checked = !toggle.checked;
      }
    };
  }
}

function _renderRagPushTable() {
  const { rows, page, pageSize, total } = RAGPUSH_STATE;
  document.getElementById("rp-results").innerHTML = card({
    title: "推送记录",
    body: `
      <table class="w-full text-sm">
        <thead class="bg-slate-50 text-slate-500 text-xs uppercase">
          <tr>
            <th class="text-left px-4 py-2">文章</th>
            <th class="px-4 py-2">来源</th>
            <th class="px-4 py-2">状态</th>
            <th class="px-4 py-2">文件数</th>
            <th class="px-4 py-2">耗时</th>
            <th class="px-4 py-2">开始时间</th>
            <th class="px-4 py-2">异常</th>
          </tr>
        </thead>
        <tbody>
          ${rows.map(r => `
            <tr class="border-t border-slate-100 hover:bg-slate-50/60">
              <td class="px-4 py-2 max-w-[420px]">
                <div class="font-medium truncate" title="${esc(r.article_title || "")}">${esc(r.article_title || "(无标题)")}</div>
                <div class="mono text-[11px] text-slate-400">#${esc(r.article_id)} · ${esc(r.site_code || "")} · ${esc(r.target_code || "")}</div>
              </td>
              <td class="px-4 py-2 text-center">${_ragPushSourcePill(r.source)}</td>
              <td class="px-4 py-2 text-center">${_ragPushStatusPill(r.status)}</td>
              <td class="px-4 py-2 text-center mono text-xs">${esc(r.file_count ?? 0)}</td>
              <td class="px-4 py-2 text-center mono text-xs">${esc(_duration(r.duration_ms))}</td>
              <td class="px-4 py-2 text-center mono text-xs text-slate-500">${fmt(r.started_at)}</td>
              <td class="px-4 py-2 text-center">
                ${r.error_msg ? `<button class="text-xs text-red-600 hover:underline" onclick="showRagPushError(${r.id})">查看</button>` : `<span class="text-slate-300">—</span>`}
              </td>
            </tr>`).join("") || `<tr><td colspan="7" class="p-8 text-center text-slate-400">暂无推送记录</td></tr>`}
        </tbody>
      </table>
      <div id="rp-pager"></div>`
  });
  window.__ragPushRows = rows;
  renderPager({
    container: document.getElementById("rp-pager"),
    total, page, pageSize,
    summary: `共 ${total} 条推送记录`,
    onPage: p => { RAGPUSH_STATE.page = p; loadRagPushLogs({ resetPage: false }); },
  });
}

function showRagPushError(id) {
  const row = (window.__ragPushRows || []).find(x => String(x.id) === String(id));
  if (!row) return;
  openModal({
    title: "RAG推送异常",
    subtitle: `${row.article_title || "无标题"} · #${row.article_id}`,
    wide: true,
    body: `<pre class="whitespace-pre-wrap text-xs bg-slate-950 text-slate-100 rounded p-4 overflow-auto max-h-[520px]">${esc(row.error_msg || "")}</pre>`,
  });
}
