import { execFileSync, spawnSync } from "node:child_process";
import { watch, writeFileSync } from "node:fs";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Checkpoint LFS objects restore with Unicode storage spaces", WEB, async ({ t3, app, browser, screen }) => {
  const results: Array<{ label: string; restored: boolean }> = [];
  for (const [label, storage] of [["trailing NBSP", "object cache\u00a0"], ["leading NBSP", "\u00a0object cache"], ["default control", ""]]) {
    const project = await t3.project(`lfs-${label.replaceAll(" ", "-")}`);
    const git = (args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" });
    git(["lfs", "install", "--local"]);
    git(["lfs", "track", "*.bin"]);
    git(["add", ".gitattributes"]);
    git(["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Track binary files"]);
    if (storage) git(["config", "lfs.storage", storage]);
    const original = `original large bytes for ${label}\n`;
    writeFileSync(`${project}/weights.bin`, original);
    const thread = await t3.thread({ project, title: `LFS checkpoint: ${label}`, messages: ["Create a checkpoint of the current workspace."] });
    const findRef = () => git(["for-each-ref", "--format=%(refname)", "refs/t3/orchestration-v2/checkpoints/"]).trim().split("\n").find(value => value.endsWith("/ordinal/1"));
    const ref = await new Promise<string>((resolve, reject) => {
      const timer = setTimeout(() => { watcher.close(); reject(new Error("Checkpoint ordinal/1 was not published")); }, 30_000);
      const check = () => { const found = findRef(); if (found) { clearTimeout(timer); watcher.close(); resolve(found); } };
      const watcher = watch(`${project}/.git`, { recursive: true }, check);
      check();
    });
    const pointer = git(["show", `${ref}:weights.bin`]);
    if (!pointer.startsWith("version https://git-lfs.github.com/spec/v1")) throw new Error("Checkpoint is not an LFS pointer");
    const smudge = spawnSync("git", ["lfs", "smudge", "weights.bin"], { cwd: project, input: pointer, encoding: "utf8" });
    const restored = smudge.status === 0 && smudge.stdout === original;
    results.push({ label, restored });
    await t3.open(thread);
    await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
    const diagnostic = ["LIVE CHECKPOINT RESTORE — runtime command results", `Case: ${label}`, `lfs.storage: ${JSON.stringify(storage || "(default)")}`, `Storage code points: ${Array.from(storage).map(c => `U+${c.codePointAt(0)!.toString(16).toUpperCase().padStart(4, "0")}`).join(" ")}`, "Checkpoint: ordinal/1", pointer.trim(), `git lfs smudge weights.bin → exit ${smudge.status}`, `Original bytes restored: ${restored ? "YES" : "NO"}`, smudge.status === 0 ? smudge.stdout.trim() : "Smudge error: object unavailable in configured LFS storage"].join("\n");
    await browser.evaluate(`(() => { document.getElementById("runtime-proof")?.remove(); const panel = document.createElement("pre"); panel.id = "runtime-proof"; panel.textContent = ${JSON.stringify(diagnostic)}; Object.assign(panel.style, {position:"fixed",left:"280px",right:"24px",top:"140px",zIndex:"99999",padding:"24px",background:"#111827",color:"#f9fafb",border:"2px solid ${restored ? "#34d399" : "#f87171"}",fontSize:"16px",lineHeight:"1.7",whiteSpace:"pre-wrap",overflowWrap:"anywhere"}); document.body.append(panel); })()`);
    await app.screenshot(label.replaceAll(" ", "-"));
  }
  expect(results, "Every checkpoint pointer must restore the original bytes through Git LFS").toEqual([
    { label: "trailing NBSP", restored: true },
    { label: "leading NBSP", restored: true },
    { label: "default control", restored: true },
  ]);
});
