/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

declare global { interface Window { proofHold: { arm: (cwd?: string) => void; requested: Promise<void>; release: () => Promise<void> } } }

test("Moved drafts resolve destination defaults, preserve choices, and cancel superseded sends", WEB, async ({t3, app, screen, browser}) => {
  const observed: Record<string, unknown> = {};
  const expected: Record<string, unknown> = {};
  const setDefault = (defaultThreadEnvMode: "local" | "worktree" | null) => runPromise(Effect.scoped(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({patch: {defaultThreadEnvMode, defaultModelSelection: {instanceId:"devReplay", model:"multi-turn"}}});
  })));
  const projects = [];
  for (const name of ["settings-source", "file-source", "explicit-source", "branch-source", "send-source"]) {
    const project = await t3.project(name, {
      ...(name === "branch-source" || name === "send-source" ? {"t3.json": '{"defaultThreadEnvMode":"worktree"}'} : {}),
      ...(name === "settings-source" ? {"destination/README.md": ""} : {"destination/t3.json": '{"defaultThreadEnvMode":"worktree"}'}),
    });
    const destination = `${project}/destination`;
    const git = (args: string[], cwd = destination) => runPromise(run("git", args, {cwd}));
    await git(["init", "--quiet", "--initial-branch=main"]);
    await git(["add", "--all"]);
    await git(["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--quiet", "-m", "Initial commit"]);
    await git(["branch", "feature"], project);
    await git(["branch", "feature"]);
    const thread = await t3.thread({project, title: `Earlier ${name}`, messages: ["hello"]});
    projects.push({name, project, destination, thread});
  }
  const repository = {".git/config": '[remote "origin"]\n\turl = https://github.com/scenario/routing.git\n'};
  const routing = await t3.project("routing", repository);
  const routingThread = await t3.thread({project:routing, title:"Earlier routing", messages:["hello"]});
  const server = startSecondServer(app.baseUrl ?? "");
  const {host, token} = await server.ready;
  const remoteProject = await makeState(SECOND_HOME).state.project("routing", {...repository, "t3.json": '{"defaultThreadEnvMode":"worktree"}'});
  await runPromise(run("git", ["branch", "-m", "remote-base"], {cwd: remoteProject}));
  await browser.addInitScript(() => {
    let target = sessionStorage.getItem("proofHoldNext");
    let armed = target !== null;
    sessionStorage.removeItem("proofHoldNext");
    let requested = Promise.withResolvers<void>();
    let releaseHeld: () => Promise<void> = async () => {};
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (!armed || typeof data !== "string") return send.call(this, data);
      const parsed = JSON.parse(data);
      const messages = [parsed].flat();
      const held = messages.filter(frame => frame.tag === "projects.readFile" && frame.payload?.relativePath === "t3.json" && (!target || frame.payload?.cwd === target));
      if (held.length === 0) return send.call(this, data);
      armed = false;
      const others = messages.filter(frame => !held.includes(frame));
      if (others.length) send.call(this, JSON.stringify(others));
      const replied = Promise.withResolvers<void>();
      this.addEventListener("message", event => {
        if ([JSON.parse(String(event.data))].flat().some(frame => frame._tag === "Exit" && String(frame.requestId) === String(held[0].id))) replied.resolve();
      });
      releaseHeld = async () => {send.call(this, Array.isArray(parsed) ? JSON.stringify(held) : data); await replied.promise;};
      requested.resolve();
    };
    window.proofHold = {
      arm: (cwd) => {requested = Promise.withResolvers<void>(); target = cwd ?? null; armed = true;},
      get requested() {return requested.promise;},
      release: () => releaseHeld(),
    };
  });
  const workspace = screen.getByRole("combobox", "Workspace", {exact:true});
  const composer = screen.getByRole("textbox");
  const picker = browser.locator("[data-draft-project-trigger]");
  const settle = () => runPromise(Effect.sleep("1 second"));
  const record = async (label: string, want: string) => {
    await settle();
    await app.screenshot(label);
    observed[label] = await browser.evaluate(() => document.querySelector('[role="combobox"][aria-label="Workspace"]')?.textContent?.trim());
    expected[label] = want;
  };
  const openDraft = async (index: number, hold = false) => {
    const entry = projects[index]!;
    if (hold) await browser.evaluate((cwd) => {sessionStorage.setItem("proofHoldNext", cwd); return null;}, entry.project);
    await t3.open(entry.thread);
    await screen.getByRole("button", `New thread in ${entry.name}`, {exact:true}).tap();
    await composer.fill(`Plan ${entry.name}`);
    if (hold) await app.screenshot(`${entry.name}-pending-default`);
    await workspace.waitFor();
  };
  const add = async (destination: string) => {
    await picker.tap();
    await screen.getByRole("option", "Add project").tap();
    await screen.getByText("Local folder").tap();
    await browser.evaluate(() => {document.querySelector<HTMLInputElement>('input[role="combobox"]')?.style.setProperty("-webkit-text-security", "disc"); return null;});
    await screen.getByRole("combobox").fill(destination);
    await browser.keyboard.press("Enter");
    await picker.getByText("destination", {exact:true}).waitFor();
  };
  const release = async () => {
    await browser.evaluate(async () => {await window.proofHold.release(); return null;});
    await settle();
  };
  try {
    await setDefault("local");
    await openDraft(0);
    await setDefault("worktree");
    await add(projects[0]!.destination);
    await record("01-global-default-after-move", "New worktree");
    await setDefault(null);

    await openDraft(1);
    await browser.evaluate((cwd) => {window.proofHold.arm(cwd); return null;}, projects[1]!.destination);
    await add(projects[1]!.destination);
    // Base never reads this file on a move. Head reads it asynchronously.
    await app.screenshot("02-file-default-before-late-read");
    await release();
    await record("03-file-default-after-late-read", "New worktree");

    await openDraft(2);
    await workspace.tap();
    await screen.getByRole("option", "New worktree", {exact:true}).tap();
    await workspace.tap();
    await screen.getByRole("option", "Current checkout", {exact:true}).tap();
    await app.screenshot("04-explicit-workspace-before-move");
    await add(projects[2]!.destination);
    await record("05-explicit-workspace-after-move", "Current checkout");

    await openDraft(3, true);
    await browser.evaluate(async () => {await window.proofHold.requested; return null;});
    await screen.getByRole("combobox", /^Branch: main/).first().tap();
    await screen.getByRole("option", /^feature\b/).tap();
    await screen.getByRole("combobox", /^Branch: feature/).first().waitFor();
    await app.screenshot("06-successful-branch-before-late-read");
    await release();
    await record("07-successful-branch-after-late-read", "Current checkout");
    await browser.evaluate((cwd) => {window.proofHold.arm(cwd); return null;}, projects[3]!.destination);
    await add(projects[3]!.destination);
    await app.screenshot("08-moved-draft-before-branch-choice");
    await screen.getByRole("combobox", /^Branch: main/).first().tap();
    await screen.getByRole("option", /^feature\b/).tap();
    await screen.getByRole("combobox", /^Branch: feature/).first().waitFor();
    await app.screenshot("08b-successful-destination-branch-before-late-default");
    await release();
    await record("08c-successful-destination-branch-after-late-default", "Current checkout");

    await openDraft(4, true);
    await browser.evaluate(async () => {await window.proofHold.requested; return null;});
    await composer.press("Enter");
    await app.screenshot("09-send-waiting-for-defaults");
    await screen.getByRole("combobox", /^Branch: main/).first().tap();
    await screen.getByRole("option", /^feature\b/).tap();
    await screen.getByRole("combobox", /^Branch: feature/).first().waitFor();
    await app.screenshot("09b-branch-choice-while-send-waits");
    await add(projects[4]!.destination);
    await settle();
    await app.screenshot("10-send-after-draft-moved-again");
    observed["cancelled-send-retains-prompt"] = await browser.evaluate(() => document.querySelector('[role="textbox"]')?.textContent?.trim());
    expected["cancelled-send-retains-prompt"] = "Plan send-source";
    // A cancelled preparation must release the send guard immediately: a deliberate new send
    // to the destination works while the old source file read is still held.
    await workspace.tap();
    await screen.getByRole("option", "Current checkout", {exact:true}).tap();
    await composer.press("Enter");
    await runPromise(Effect.sleep("2 seconds"));
    await app.screenshot("10b-new-send-after-move-before-old-read-released");
    observed["new-send-is-not-blocked-by-old-default"] = await browser.evaluate(() => document.querySelector('[role="textbox"]')?.textContent?.trim());
    expected["new-send-is-not-blocked-by-old-default"] = "";
    await release();
    await app.screenshot("10c-old-read-released-no-stale-send");

    await t3.open(routingThread);
    await screen.getByRole("button", "New thread in routing", {exact:true}).tap();
    await composer.fill("Plan the remote change");
    const draftPath = new URL(await browser.url()).pathname;
    await app.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await browser.evaluate(() => {document.querySelector<HTMLInputElement>('input[placeholder="PAIRCODE"]')?.setAttribute("type", "password"); return null;});
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByRole("button", "List", {exact:true}).tap();
    await screen.getByRole("button", "More actions for Scenario").waitFor({timeout:60_000});
    await app.open(draftPath);
    await browser.evaluate((cwd) => {window.proofHold.arm(cwd); return null;}, remoteProject);
    await screen.getByRole("combobox", "Run on", {exact:true}).tap();
    await screen.getByRole("option", "Scenario", {exact:true}).nth(1).tap();
    await browser.evaluate(async () => {await window.proofHold.requested; return null;});
    await app.screenshot("11-environment-retarget-before-late-default");
    await release();
    await screen.getByRole("combobox", /^Branch: (From )?remote-base/).first().waitFor();
    await record("12-environment-retarget-default", "New worktree");
    await expect(observed).toEqual(expected);
  } finally {
    await server.stop();
  }
});
