<h1>Pipeline</h1>
<div class="stages" id="stages"></div>

<h2 id="activity">Activity</h2>
<div id="jobstate" aria-live="polite">idle</div>
<div id="joblog" role="log" aria-label="stage output">(stage output appears here)</div>
<script>
"use strict";
let P = null;
let RUNNING = false;

async function runStage(stage, body) {
  const res = await apiPost(`/api/run/${stage}`, body);
  if (res) refresh().catch(() => {});  // the poll self-heals a hiccup
}

function stageCard(num, name, facts, actions) {
  return `<section class="stage">
    <div class="top"><span class="num">${num}</span><span class="name">${name}</span></div>
    <div class="facts">${facts}</div>
    <div class="act">${actions}</div>
  </section>`;
}

function runBtn(stage, label) {
  return `<button class="primary" data-run="${stage}" ${RUNNING ? "disabled" : ""}>${esc(label ?? "Run")}</button>`;
}

function render() {
  const m = P.matches, log = P.upload_log;
  RUNNING = P.job.status === "running";  // buttons below depend on this

  const banners = [];
  if (P.stub_data) banners.push(
    `<div class="banner warn">Stub fixtures active: resolved ids are placeholders and the
     real upload stays locked until real BGG data replaces them.</div>`);
  const missing = Object.entries(P.env).filter(([, ok]) => !ok).map(([k]) => k);
  if (missing.length) banners.push(
    `<div class="banner warn">Credentials not loaded in this server's environment:
     ${missing.map(esc).join(", ")} — run <code>bggpipe init</code> or load .env, then restart.</div>`);
  showBanner(banners.join(""));

  const uploadFacts = `<b>${P.to_add}</b> to add · <b>${P.to_update}</b> version updates
    ${log.added || log.added_no_version ? `· <b>${(log.added ?? 0) + (log.added_no_version ?? 0)}</b> added` : ""}
    ${P.upload_failed ? `· <b>${P.upload_failed}</b> failed` : ""}
    · <a href="/queue">inspect the queue</a>
    ${!P.to_add && !P.to_update && P.queued_total
      ? `<br><span class="meta">${P.queued_total} queued row(s) already applied —
         the next <b>diff</b> clears them (BGG's collection export can lag the
         site by a while)</span>`
      : ""}`;

  document.getElementById("stages").innerHTML = [
    stageCard(1, "extract", `read titles off <b>${P.photos}</b> <a href="/photos">photo(s)</a> — <b>${P.titles}</b> so far`
      + (P.titles > 0
          ? P.shaky_reads > 0
            ? ` · <b>${P.shaky_reads}</b> shaky read(s) worth a <a href="/titles">proofread</a> before resolving`
            : ` · <a href="/titles">proofread the titles</a> before resolving`
          : ""), runBtn("extract")),
    stageCard(2, "resolve", `match titles to BGG ids — <b>${(m.auto ?? 0)}</b> auto · <b>${m.ambiguous ?? 0}</b> ambiguous · <b>${m.unmatched ?? 0}</b> unmatched`, runBtn("resolve")),
    stageCard(3, "review", `<b>${P.pending_review}</b> item(s) waiting for your call`, `<a class="linkbtn" href="/review">Open review</a>`),
    stageCard(4, "diff", `compare against your BGG collection`, runBtn("diff")),
    stageCard(5, "upload", uploadFacts,
      `${runBtn("upload", "Dry run")}
       <button class="danger" data-upload-real ${RUNNING || P.stub_data ? "disabled" : ""}>Upload</button>
       <label>limit <input type="number" id="uplimit" min="1" placeholder="all"></label>
       ${P.upload_failed
         ? `<label title="failed jobs are skipped on normal runs so a broken one can't loop">
              <input type="checkbox" id="upretry"> retry ${P.upload_failed} failed</label>`
         : ""}`),
    stageCard(6, "enrich", `<b>${P.games}</b> game(s) in the <a href="/library">library</a>`, runBtn("enrich")),
  ].join("");

  document.querySelectorAll("[data-run]").forEach(b =>
    b.addEventListener("click", () => runStage(b.dataset.run,
      b.dataset.run === "upload" ? {dry_run: true, ...uploadOpts()} : {})));
  const uploadOpts = () => ({
    limit: Number(document.getElementById("uplimit").value) || null,
    retry_failed: !!document.getElementById("upretry")?.checked,
  });
  const real = document.querySelector("[data-upload-real]");
  if (real) real.addEventListener("click", () => {
    const {limit, retry_failed} = uploadOpts();
    if (!confirm(`Really add games to your live BGG collection${limit ? ` (limit ${limit})` : ""}` +
                 `${retry_failed ? ", retrying previously failed jobs" : ""}? A browser window will open.`)) return;
    runStage("upload", {dry_run: false, limit, retry_failed});
  });

  const job = P.job;
  const state = document.getElementById("jobstate");
  if (job.status === "idle") state.textContent = "idle";
  // s- prefix: a bare status class collides with page classes (.done is
  // the review celebration card)
  else state.innerHTML = `<span class="s-${esc(job.status)}">${esc(job.stage)}: ${esc(job.status)}</span>` +
    (job.error ? ` — ${esc(job.error)}` : "");
  const logEl = document.getElementById("joblog");
  const atBottom = logEl.scrollTop + logEl.clientHeight >= logEl.scrollHeight - 4;
  logEl.textContent = job.log.length ? job.log.join("\n") : "(stage output appears here)";
  if (atBottom) logEl.scrollTop = logEl.scrollHeight;
}

const GATE = changeGate();
async function refresh() {
  const p = await fetchJSON("/api/pipeline");
  GATE(p, () => { P = p; render(); });
}

refresh().catch(err => errorBanner(err.message || err));
pollLoop(refresh, 2000, () => render());
</script>
