import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

// Run with race-hook.mjs via NODE_OPTIONS on both revisions. The hook supplies synthetic
// forge updates, makes replay turns last three seconds, and delays completion queue promotion
// four seconds outside the thread lock. The real settlement service remains unchanged.
const fixture = async (path: string, threadId: string) => {
  const response = await fetch(`http://127.0.0.1:${process.env.PROOF_RACE_PORT}${path}`, {
    method: "POST", body: JSON.stringify({ threadId }),
  });
  if (!response.ok) throw new Error(await response.text());
  return response.json();
};

test("A merged PR watch wake runs before automatic settlement", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("merge-wake-demo");
  const thread = await t3.thread({ project, title: "Merge notification delivery", messages: ["Prepare to watch the pull request."], model: "multi-turn" });
  await t3.open(thread);
  await screen.getByText("first fixture turn complete").waitFor({ state: "visible", timeout: 60000 });
  await fixture("/prepare", thread.threadId);
  const { cli } = makeState(T3_HOME);
  await runPromise(cli(["thread", "send", thread.threadId, "Finish the current work while the watched pull request merges.", "--json"]));
  const merged = await fixture("/merge", thread.threadId);
  if (!merged.runs.some((run: any) => run.status === "queued" && run.userMessageId === "proof-merge-wake")) throw new Error("Fixture did not queue the watch wake behind the active turn");
  await screen.getByRole("button", "Stop generation").waitFor({ state: "visible", timeout: 60000 });
  await app.screenshot("wake-queued");
  // Wait for both the active replay and the delayed promotion; capture before asserting so
  // the base gets the same labelled result image as the fix.
  await new Promise(resolve => setTimeout(resolve, 13000));
  await app.screenshot("merge-wake-result");
  const final = await fixture("/state", thread.threadId);
  const wake = final.runs.find((run: any) => run.userMessageId === "proof-merge-wake");
  await expect(wake?.status).toBe("completed");
});
