import { chmod, writeFile, readFile } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Unreadable workspace files do not prevent turn checkpoints", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Unreadable files", {
    "locked.txt": "committed\n",
    "readme.txt": "Checkpoint reproduction\n",
  });
  await writeFile(`${project}/locked.txt`, "changed\n");
  await writeFile(`${project}/untracked-secret.txt`, "secret\n");
  await chmod(`${project}/locked.txt`, 0);
  await chmod(`${project}/untracked-secret.txt`, 0);
  const thread = await t3.thread({ project, title: "Checkpoint with unreadable files", model: "command-output", messages: ["go"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  const ready = `${project}/../shell-ready`;
  let started = false;
  for (let attempt = 0; attempt < 30; attempt++) {
    await terminal.focus();
    await browser.keyboard.type("PS1='$ '; clear; echo ready > ../shell-ready");
    await browser.keyboard.press("Enter");
    try { started = (await readFile(ready, "utf8")).includes("ready"); } catch {}
    if (started) break;
    await new Promise(resolve => setTimeout(resolve, 500));
  }
  if (!started) throw new Error("terminal shell did not become ready");
  await terminal.focus();
  await browser.keyboard.type(`PS1='$ '; clear; printf 'Unreadable-file checkpoint reproduction\\nLinux, non-root user; completed replay turn\\n\\n'; stat -c '%a %n' locked.txt untracked-secret.txt; printf '\\nCheckpoint refs (baseline and end of turn):\\n'; git for-each-ref --format='%(refname)' refs/t3 | sed -E 's@/[^/]+/ordinal/@/THREAD/ordinal/@g'; printf 'Total checkpoint refs: '; git for-each-ref refs/t3 | wc -l`);
  await browser.keyboard.press("Enter");
  await new Promise(resolve => setTimeout(resolve, 1000));
  await app.screenshot("checkpoint-refs");
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" }).trim();
  const refs = git("for-each-ref", "--format=%(refname)", "refs/t3").split("\n").filter(Boolean);
  console.log("Checkpoint refs:", refs.map(r => r.replace(thread.threadId, "THREAD")));
  await expect(refs.length).toBe(2);
  for (const ref of refs) {
    await expect(git("show", `${ref}:locked.txt`)).toBe("committed");
    await expect(git("ls-tree", "--name-only", ref)).not.toContain("untracked-secret.txt");
  }
});
