/// <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 {
    destinationGate: { requested: Promise<void>; release: () => Promise<void> };
  }
}

test("Editing or leaving a draft abandons destination workspace preparation", WEB, async ({ t3, app, screen, browser }) => {
  const repository = { ".git/config": '[remote "origin"]\n\turl = https://github.com/scenario/demo.git\n' };
  const source = await t3.project("demo", repository);
  await runPromise(run("git", ["branch", "-m", "source-only"], { cwd: source }));
  const second = makeState(SECOND_HOME);
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    const destination = await second.state.project("demo", { ...repository, "t3.json": '{"defaultThreadEnvMode":"worktree"}' });
    await runPromise(run("git", ["branch", "-m", "remote-base"], { cwd: destination }));
    const localOrigin = `${destination}/../origin.git`;
    await runPromise(run("git", ["clone", "--bare", destination, localOrigin]));
    for (const cwd of [source, destination]) await runPromise(run("git", ["config", `url.${localOrigin}.insteadOf`, "https://github.com/scenario/demo.git"], { cwd }));
    await runPromise(Effect.scoped(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["server.updateSettings"]({ patch: { defaultThreadEnvMode: "worktree", newWorktreesStartFromOrigin: false } });
    })));
    await browser.addInitScript(({ source, destination }) => {
      new MutationObserver(() => {
        const pairing = document.querySelector('input[placeholder="PAIRCODE"]');
        if (pairing instanceof HTMLInputElement) pairing.type = "password";
        if (!document.body) return;
        const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
        for (let node = walker.nextNode(); node; node = walker.nextNode()) {
          const old = node.textContent ?? "";
          const next = old.replaceAll(source, "[source repository]").replaceAll(destination, "[destination repository]");
          if (next !== old) node.textContent = next;
        }
      }).observe(document, { childList: true, subtree: true, characterData: true });
    }, { source, destination });
    const capture = async (label: string) => {
      // Evidence pacing only; the UI waits above each call establish its state.
      await new Promise((resolve) => setTimeout(resolve, 1500));
      await app.screenshot(label);
    };
    await t3.open();
    await screen.getByRole("textbox").fill("Edit during destination preparation");
    await app.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const pairing = screen.getByRole("dialog");
    await pairing.getByPlaceholder("backend.example.com").fill(host);
    await pairing.getByPlaceholder("PAIRCODE").fill(token);
    await pairing.getByRole("button", "Add environment").tap();
    await screen.getByRole("switch", "Automatically balance load").tap();
    const preferences = async (sourcePreference: string, destinationPreference: string) => {
      await app.open("/settings/connections");
      await screen.getByRole("button", /^Load balancing/).tap();
      const choices = screen.getByRole("combobox", "Scenario load preference");
      await choices.first().tap();
      await screen.getByRole("option", sourcePreference, { exact: true }).tap();
      await choices.last().tap();
      await screen.getByRole("option", destinationPreference, { exact: true }).tap();
    };
    const sourceDraft = async (prompt: string) => {
      await preferences("Normal", "Manual only");
      await t3.open();
      const runOn = screen.getByRole("combobox", "Run on", { exact: true });
      await runOn.tap();
      await screen.getByRole("option", "Scenario", { exact: true }).first().tap();
      await runOn.tap();
      await screen.getByRole("option", "Auto balance", { exact: true }).tap();
      await screen.getByRole("textbox").fill(prompt);
      await runOn.getByText("Auto balance", { exact: true }).waitFor();
      await screen.getByRole("combobox", /^Branch: (From )?source-only/).first().waitFor();
      await browser.locator("[data-chat-provider-model-picker-label]").first().tap();
      await browser.keyboard.type("Multi turn");
      await browser.keyboard.press("Enter");
      await browser.keyboard.press("Escape");
      const draft = new URL(await browser.url()).pathname;
      await preferences("Manual only", "Normal");
      await app.open(draft);
      await screen.getByRole("combobox", /^Branch: (From )?source-only/).first().waitFor();
      return draft;
    };
    const gateDestinationRead = async () => {
      await browser.evaluate(({ destination }) => {
        const requested = Promise.withResolvers<void>();
        const replied = Promise.withResolvers<void>();
        let release = () => {};
        const send = WebSocket.prototype.send;
        WebSocket.prototype.send = function(data) {
          if (typeof data !== "string" || !data.includes('"relativePath":"t3.json"')) return send.call(this, data);
          const parsed = JSON.parse(data);
          type Frame = { tag?: string; id?: string; payload?: { cwd?: string; relativePath?: string } };
          const frames: Frame[] = [parsed].flat();
          const matches = (frame: Frame) => frame.tag === "projects.readFile" && frame.payload?.cwd === destination && frame.payload?.relativePath === "t3.json";
          const held = frames.filter(matches);
          if (!held.length) return send.call(this, data);
          const others = frames.filter((frame) => !matches(frame));
          if (others.length) send.call(this, JSON.stringify(others));
          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();
          });
          release = () => send.call(this, Array.isArray(parsed) ? JSON.stringify(held) : data);
          requested.resolve();
        };
        window.destinationGate = { requested: requested.promise, release: async () => { release(); await replied.promise; } };
        return null;
      }, { destination });
    };
    const waitForPreparationOrBaseFailure = () => browser.evaluate(async () => {
      const submitted = new Promise<"submitted">((resolve) => {
        const check = () => {
          if (/Base ref|first fixture turn complete|Workspace preparation failed/.test(document.body.textContent ?? "")) {
            observer.disconnect(); resolve("submitted");
          }
        };
        const observer = new MutationObserver(check);
        observer.observe(document.body, { childList: true, subtree: true, characterData: true });
        check();
      });
      return await Promise.race([window.destinationGate.requested.then(() => "held" as const), submitted]);
    });
    await sourceDraft("Edit during destination preparation");
    await capture("edit-before-send");
    await gateDestinationRead();
    await screen.getByRole("textbox").press("Enter");
    const editPreparation = await waitForPreparationOrBaseFailure();
    await screen.getByRole("textbox").fill("Unsubmitted replacement");
    if (editPreparation === "held") await browser.evaluate(async () => { await window.destinationGate.release(); return null; });
    await screen.getByText(/Draft changed while preparing this message|Base ref|Workspace preparation failed/).first().waitFor();
    await capture("edited-draft-after-preparation-settles");
    const editedSafely = await browser.evaluate(() => (document.body.textContent ?? "").includes("Draft changed while preparing this message. Review it and send again.") && !(document.body.textContent ?? "").includes("Base ref"));

    const closedDraft = await sourceDraft("Close during destination preparation");
    await capture("close-before-send");
    await gateDestinationRead();
    await screen.getByRole("textbox").press("Enter");
    const closePreparation = await waitForPreparationOrBaseFailure();
    await screen.getByRole("button", "New thread", { exact: true }).tap();
    if (closePreparation === "held") await browser.evaluate(async () => { await window.destinationGate.release(); return null; });
    await capture("new-draft-after-leaving-preparation");
    await app.open(closedDraft);
    await screen.getByRole("textbox").waitFor();
    await capture("reopened-draft-after-leaving-preparation");
    await expect(editedSafely).toBe(true);
    await expect(screen.getByRole("textbox")).toHaveText("Close during destination preparation");
    await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeHidden();
  } finally { await server.stop(); }
});
