/// <reference lib="dom" />
import { readFile, writeFile, chmod, unlink } from "node:fs/promises";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Retry after a failed checkout hook runs project setup before the next turn", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("checkout-retry", {"README.md": "# Checkout setup status\n\nsetup-ready is MISSING. Project setup has not run in this checkout.\n"});
  const git = async (...args: string[]) => (await runPromise(run("git", args, {cwd: project}))).stdout;
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    yield* client["server.updateSettings"]({patch: {defaultProjectScripts: [{id:"setup-proof", name:"Write setup-ready", command:"date -u > setup-ready && printf '# Checkout setup status\\n\\nProject setup ran successfully. setup-ready timestamp:\\n' > README.md && cat setup-ready >> README.md", icon:"play", runOnWorktreeCreate:true, async:false}]}});
    yield* client.subscribeServerConfig({}).pipe(Stream.filter(event => {
      const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
      return providers.some(p => p.instanceId === "devReplay" && p.models.some(m => m.slug === "multi-turn"));
    }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const {cli} = makeState(T3_HOME);
  const usedCheckouts = new Set<string>();
  const start = async (title: string) => {
    const result = await runPromise(cli(["thread","start",project,"Start here","--title",title,"--worktree","main","--provider","devReplay","--model","multi-turn","--wait","--json"]));
    const thread = JSON.parse(result.stdout) as {threadId:string};
    const entries = (await git("worktree","list","--porcelain")).split("\n\n");
    const checkout = entries.map(e => e.split("\n")[0]?.slice(9)).filter(p => p && p !== project && !usedCheckouts.has(p)).at(-1);
    if (!checkout) throw new Error("Missing managed checkout");
    usedCheckouts.add(checkout);
    await readFile(`${checkout}/setup-ready`, "utf8");
    return {...thread, checkout};
  };
  const control = await start("Normal restore control");
  await git("worktree","remove","--force",control.checkout);
  await runPromise(cli(["thread","send",control.threadId,"Normal restore","--wait","--json"]));
  await readFile(`${control.checkout}/setup-ready`, "utf8");
  const thread = await start("Checkout hook retry");
  await git("worktree","remove","--force",thread.checkout);
  const hook = `${project}/.git/hooks/post-checkout`;
  await writeFile(hook, "#!/bin/sh\nexit 1\n");
  await chmod(hook, 0o755);
  const failed = await runPromise(cli(["thread","send",thread.threadId,"Continue here","--wait","--json"], [1]));
  if (!`${failed.stdout}${failed.stderr}`.includes("recreate")) throw new Error("Send did not fail during checkout recreation");
  await readFile(`${thread.checkout}/.git`, "utf8");
  await unlink(hook);
  await runPromise(cli(["thread","send",thread.threadId,"Try again","--wait","--json"]));
  const ready = await readFile(`${thread.checkout}/setup-ready`, "utf8").catch(() => "");
  await t3.open(thread);
  await screen.getByText("second fixture turn complete", {exact:false}).waitFor();
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", {exact:true}).tap();
  await browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const row = host.shadowRoot?.querySelector<HTMLElement>('[data-item-path="README.md"]');
      if (row) { row.click(); return true; }
    }
    return false;
  });
  // File tree population is asynchronous; retry opening until the editor is visible.
  await expect.poll(async () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content?.textContent?.includes("Checkout setup status")) return true;
      host.shadowRoot?.querySelector<HTMLElement>('[data-item-path="README.md"]')?.click();
    }
    return false;
  })).toBe(true);
  await app.screenshot("retry-setup-result");
  await expect(ready.length > 0).toBe(true);
});
