// SPDX-License-Identifier: Apache-2.0
//
// run.mjs: the page script of /verify/run.html. It checks a Handoff v0 export with the verifier kit, in this page.
// Nothing the user pastes or opens is sent anywhere: the only requests are same-origin GETs, for the kit module, the
// samples under /verify/r8.1a/ and, when the suite runs, the fixtures under /spec/handoff/v0/fixtures/.
// All text from the kit is inserted with textContent, never as markup.

import { verifyRecord, runConformance, bytesStripNonEmpty } from "/verify/kit/handoff-verify.mjs";

const $ = (id) => document.getElementById(id);
const fields = ["export", "keys", "known"];
const bytes = { export: null, keys: null, known: null };
const SAMPLE = "/verify/r8.1a/";
const FIXTURES = "/spec/handoff/v0/fixtures/";
const SHOW_LIMIT = 1024 * 1024;

const getBytes = async (path) => {
  const r = await fetch(path, { credentials: "omit" });
  if (!r.ok) throw new Error(`HTTP ${r.status} for ${path}`);
  return new Uint8Array(await r.arrayBuffer());
};

function setFile(field, u8, label) {
  bytes[field] = u8;
  $("name-" + field).textContent = `${label}, ${u8.length} bytes`;
  $("in-" + field).value = u8.length <= SHOW_LIMIT ? new TextDecoder("utf-8").decode(u8) : "";
}

for (const f of fields) {
  $("in-" + f).addEventListener("input", () => {
    bytes[f] = null;
    $("name-" + f).textContent = "";
  });
}

let pickFor = null;
for (const b of document.querySelectorAll("[data-open]")) {
  b.addEventListener("click", () => {
    pickFor = b.getAttribute("data-open").slice(3);
    $("file-pick").value = "";
    $("file-pick").click();
  });
}
// A failed sample fetch or file read clears the previous result and shows the error in its place.
function loadFailed(e) {
  for (const el of $("result").querySelectorAll("[data-verdict]")) el.hidden = true;
  $("record-state").hidden = true;
  $("no-witness").hidden = true;
  $("findings-list").replaceChildren(li([["level", "ERROR"], ["msg", e && e.message ? e.message : String(e)]]));
  $("time-list").replaceChildren();
  document.body.removeAttribute("data-last-result");
  $("result").hidden = false;
}

$("file-pick").addEventListener("change", async (ev) => {
  const file = ev.target.files && ev.target.files[0];
  if (!file || !pickFor) return;
  try {
    setFile(pickFor, new Uint8Array(await file.arrayBuffer()), file.name);
  } catch (e) {
    loadFailed(e);
  }
});

async function loadSample(name) {
  const [exp, keys] = await Promise.all([getBytes(SAMPLE + name), getBytes(SAMPLE + "keys.json")]);
  setFile("export", exp, name);
  setFile("keys", keys, "keys.json");
  bytes.known = null;
  $("in-known").value = "";
  $("name-known").textContent = "";
}

function splitLines(b) {
  // one signed head per line; \n, \r\n and \r end a line, as the command line reads --known-heads
  const out = [];
  let s = 0;
  for (let i = 0; i < b.length; i++) {
    if (b[i] === 0x0a || b[i] === 0x0d) {
      out.push(b.slice(s, i));
      if (b[i] === 0x0d && b[i + 1] === 0x0a) i++;
      s = i + 1;
    }
  }
  if (s < b.length) out.push(b.slice(s));
  return out.filter(bytesStripNonEmpty);
}

function inputs() {
  const text = (f) => $("in-" + f).value;
  const exp = bytes.export ?? text("export");
  const keys = bytes.keys ?? (text("keys").trim() ? text("keys") : null);
  let known = bytes.known ?? (text("known").trim() ? new TextEncoder().encode(text("known")) : null);
  if (known !== null) known = splitLines(known);
  if (known !== null && !known.length) known = null;
  return { exp, opts: { keysBytes: keys, knownLines: known } };
}

// Read-only adapter for the local-package UI. Copies the exact inputs used by Check;
// never exposes account state or alters retained file bytes.
export function currentCheckerInputBytes() {
  const copy = (value) => typeof value === "string" ? new TextEncoder().encode(value) : value === null ? new Uint8Array() : new Uint8Array(value).slice();
  return { export: copy(bytes.export ?? $("in-export").value), keys: copy(bytes.keys ?? $("in-keys").value), knownHeads: copy(bytes.known ?? $("in-known").value) };
}

function li(parts) {
  const el = document.createElement("li");
  for (const [cls, txt] of parts) {
    if (txt === null || txt === undefined || txt === "") continue;
    const s = document.createElement(cls === "msg" ? "span" : "code");
    s.className = "f-" + cls;
    s.textContent = String(txt);
    el.append(s, " ");
  }
  return el;
}

function show(report) {
  const res = $("result");
  for (const el of res.querySelectorAll("[data-verdict]")) el.hidden = el.getAttribute("data-verdict") !== report.result;
  const state = report.findings.find((f) => f.code === "RECORD_STATE");
  $("record-state").hidden = !state;
  $("record-state-line").textContent = state ? state.message : "";
  $("no-witness").hidden = !report.findings.some((f) => f.code === "NO_WITNESS");
  const list = $("findings-list");
  list.replaceChildren(...report.findings.map((f) => li([
    ["level", f.level], ["code", f.code], ["seq", f.seq === null ? "" : "seq " + f.seq], ["class", f.class ? "class " + f.class : ""],
    ["msg", f.message],
  ])));
  $("time-list").replaceChildren(...(report.time_bounds || []).map((t) => li([["seq", "seq " + t.seq], ["code", t.type], ["msg", t.statement]])));
  res.hidden = false;
}

$("checker").addEventListener("submit", (ev) => {
  ev.preventDefault();
  const btn = $("btn-check");
  btn.disabled = true;
  // let the page repaint before the synchronous check
  setTimeout(() => {
    try {
      const { exp, opts } = inputs();
      const report = verifyRecord(exp, opts);
      show(report);
      document.body.setAttribute("data-last-result", report.result);
      $("result").scrollIntoView({ block: "start" });
    } finally {
      btn.disabled = false;
    }
  }, 0);
});

$("btn-sample").addEventListener("click", () => loadSample("V01-1.export.json").catch(loadFailed));
$("btn-changed").addEventListener("click", () => loadSample("V02-1.export.json").catch(loadFailed));

$("btn-suite").addEventListener("click", async () => {
  const btn = $("btn-suite");
  btn.disabled = true;
  const fails = $("suite-fails");
  fails.replaceChildren();
  $("suite-total").hidden = false;
  let n = 0;
  $("suite-n").textContent = "0";
  try {
    const res = await runConformance((name) => getBytes(FIXTURES + name), {
      onCase: (c) => {
        if (c.pass) n++;
        else fails.append(li([["level", "FAIL"], ["code", c.id], ["msg", c.why]]));
        $("suite-n").textContent = String(n);
      },
      pause: () => new Promise((r) => setTimeout(r, 0)),
    });
    document.body.setAttribute("data-suite", `${res.pass}/${res.fixtures}`);
  } catch (e) {
    fails.append(li([["level", "ERROR"], ["msg", e && e.message ? e.message : String(e)]]));
    document.body.setAttribute("data-suite", "error");
  } finally {
    btn.disabled = false;
  }
});

document.body.setAttribute("data-ready", "1");
