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

test("Moved drafts adopt destination defaults and preserve choices and cancelled sends", WEB, async ({ t3, app, screen, browser }) => {
  const repo = { ".git/config": '[remote "origin"]\n\turl = https://github.com/scenario/draft-proof.git\n' };
  const source = await t3.project("source", { ...repo, "alpha/README.md": "", "delta/t3.json": '{"defaultThreadEnvMode":"worktree"}', "explicit/t3.json": '{"defaultThreadEnvMode":"worktree"}', "branch-choice/t3.json": '{"defaultThreadEnvMode":"worktree"}' });
  const pending = await t3.project("pending-source", { "t3.json": '{"defaultThreadEnvMode":"local"}' });
  const branchInitial = await t3.project("branch-initial", { "t3.json": '{"defaultThreadEnvMode":"worktree"}' });
  await runPromise(run("git", ["branch", "feature-proof"], { cwd: branchInitial }));
  const branchAnchor = await t3.thread({ project: branchInitial, title: "Branch anchor", messages: ["first"] });
  const final = await t3.project("final-destination");
  const anchor = await t3.thread({ project: source, title: "Source anchor", messages: ["first"] });
  const pendingAnchor = await t3.thread({ project: pending, title: "Pending anchor", messages: ["first"] });
  await t3.thread({ project: final, title: "Final anchor", messages: ["first"] });
  for (const name of ["alpha", "delta", "explicit", "branch-choice"]) {
    const cwd = `${source}/${name}`;
    for (const args of [["init", "--quiet", "--initial-branch=main"], ["add", "."], ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--quiet", "-m", "Initial commit"], ["branch", "feature-proof"]]) await runPromise(run("git", args, { cwd }));
  }
  const settings = (defaultThreadEnvMode: "local" | "worktree" | null) => runPromise(Effect.scoped(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { defaultThreadEnvMode } });
  })));
  await browser.emulateMedia({ colorScheme: "light", reducedMotion: "reduce" });
  await browser.addInitScript(() => {
    const requested = Promise.withResolvers<void>();
    const replied = Promise.withResolvers<void>();
    let sendHeld = () => {};
    const send = WebSocket.prototype.send;
    window.proofHold = { suffix: "", requested: requested.promise, release: async () => { sendHeld(); await replied.promise; } };
    WebSocket.prototype.send = function(data) {
      if (typeof data !== "string" || !window.proofHold.suffix || !data.includes('"relativePath":"t3.json"')) return send.call(this, data);
      const parsed = JSON.parse(data);
      const frames = [parsed].flat();
      const held = frames.filter(f => f.tag === "projects.readFile" && f.payload?.relativePath === "t3.json" && JSON.stringify(f.payload).includes(window.proofHold.suffix));
      if (!held.length) return send.call(this, data);
      const rest = frames.filter(f => !held.includes(f));
      if (rest.length) send.call(this, JSON.stringify(rest));
      this.addEventListener("message", event => {
        if ([JSON.parse(String(event.data))].flat().some(f => f._tag === "Exit" && String(f.requestId) === String(held[0].id))) replied.resolve();
      });
      sendHeld = () => send.call(this, Array.isArray(parsed) ? JSON.stringify(held) : data);
      requested.resolve();
    };
  });
  const workspace = screen.getByRole("combobox", "Workspace", { exact: true });
  const picker = browser.locator("[data-draft-project-trigger]");
  const composer = screen.getByRole("textbox");
  const observations: Record<string, string | boolean> = {};
  const readWorkspace = () => browser.evaluate(() => document.querySelector('[role="combobox"][aria-label="Workspace"]')?.textContent?.trim() ?? "missing");
  const start = async (prompt: string) => {
    await t3.open(anchor);
    await screen.getByRole("button", "New thread in source", { exact: true }).tap();
    await workspace.waitFor();
    await composer.fill(prompt);
  };
  const add = async (name: string) => {
    await picker.tap();
    await screen.getByRole("option", "Add project", { exact: true }).tap();
    await screen.getByText("Local folder", { exact: true }).tap();
    await screen.getByRole("combobox").fill(`${source}/${name}`);
    await browser.keyboard.press("Enter");
    await picker.getByText(name, { exact: true }).waitFor();
    await browser.locator('[data-slot="command-dialog-popup"]').waitFor({ state: "detached" });
  };
  const capture = async (label: string) => { await app.screenshot(label); observations[label] = await readWorkspace(); };
  try {
    await settings("local");
    await start("Plan alpha with inherited settings");
    await workspace.getByText("Current checkout").waitFor();
    await settings("worktree");
    await add("alpha");
    await capture("01-global-default-after-add");

    await settings(null);
    await start("Plan delta with its project file");
    await add("delta");
    await capture("02-project-file-after-add");

    await start("Keep my explicit checkout choice");
    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("03-explicit-choice-before-move");
    await add("explicit");
    await capture("04-explicit-choice-after-move");

    await start("Keep my successful branch choice");
    await browser.evaluate(() => { window.proofHold.suffix = "/branch-choice"; return null; });
    await add("branch-choice");
    await browser.evaluate(async () => { await window.proofHold.requested; return null; });
    await screen.getByRole("combobox", "Branch: main", { exact: true }).first().tap();
    await screen.getByRole("option", "feature-proof", { exact: false }).tap();
    await screen.getByRole("combobox", "Branch: feature-proof", { exact: true }).first().waitFor();
    await expect.poll(async () => (await runPromise(run("git", ["branch", "--show-current"], { cwd: `${source}/branch-choice` }))).stdout.trim()).toBe("feature-proof");
    await expect(screen.getByRole("combobox", "Branch: feature-proof", { exact: true }).first()).toBeEnabled();
    await app.screenshot("05-branch-chosen-while-default-pending");
    await browser.evaluate(async () => { await window.proofHold.release(); return null; });
    await capture("06-successful-branch-after-default");

    // Reuse an empty draft whose machine choice is already manual, so the older
    // manual-environment guard cannot conceal a late default overwriting a branch.
    await t3.open(branchAnchor);
    await screen.getByRole("button", "New thread in branch-initial", { exact: true }).tap();
    await workspace.getByText("New worktree", { exact: true }).waitFor();
    await screen.getByRole("combobox", /^Branch: From main/).first().tap();
    await screen.getByRole("option", "feature-proof", { exact: false }).tap();
    await t3.open(branchAnchor);
    await browser.evaluate(() => { window.proofHold.suffix = "/branch-initial"; return null; });
    await screen.getByRole("button", "New thread in branch-initial", { exact: true }).tap();
    await browser.evaluate(async () => { await window.proofHold.requested; return null; });
    await composer.fill("Use the branch I selected while defaults load");
    await screen.getByRole("combobox", "Branch: main", { exact: true }).first().tap();
    await screen.getByRole("option", "feature-proof", { exact: false }).tap();
    await expect.poll(async () => (await runPromise(run("git", ["branch", "--show-current"], { cwd: branchInitial }))).stdout.trim()).toBe("feature-proof");
    await expect(screen.getByRole("combobox", "Branch: feature-proof", { exact: true }).first()).toBeEnabled();
    await app.screenshot("06b-initial-branch-choice-before-default");
    await browser.evaluate(async () => { await window.proofHold.release(); return null; });
    await capture("06c-initial-branch-choice-after-default");

    // Reload gives the source project an uncached file read, held before opening its draft.
    await t3.open(pendingAnchor);
    await browser.evaluate(() => { window.proofHold.suffix = "/pending-source"; return null; });
    await screen.getByRole("button", "New thread in pending-source", { exact: true }).tap();
    await browser.evaluate(async () => { await window.proofHold.requested; return null; });
    await screen.getByRole("button", "Showcase", { exact: true }).tap();
    await browser.keyboard.type("Plan and reads");
    await browser.keyboard.press("Enter");
    await browser.keyboard.press("Escape");
    await composer.fill("This send must be cancelled if I move");
    await app.screenshot("07a-send-ready-before-enter");
    await composer.press("Enter");
    await app.screenshot("07-send-waiting-for-default");
    await picker.tap(); await screen.getByRole("option", "final-destination", { exact: true }).tap();
    await picker.getByText("final-destination", { exact: true }).waitFor();
    await browser.evaluate(async () => { await window.proofHold.release(); return null; });
    const second = makeState(SECOND_HOME);
    const server = startSecondServer(app.baseUrl ?? "");
    try {
      const { host, token } = await server.ready;
      const remoteProject = await second.state.project("source", { ...repo, "t3.json": '{"defaultThreadEnvMode":"worktree"}' });
      await runPromise(run("git", ["branch", "-m", "remote-base"], { cwd: remoteProject }));
      await app.screenshot("08-send-after-second-move");
      observations.cancelledSend = await browser.evaluate(() => !!document.querySelector('[data-draft-project-trigger]') && !!document.querySelector('[contenteditable="true"]')?.textContent?.includes("This send must be cancelled"));
      await start("Retarget to the other environment");
      const path = new URL(await browser.url()).pathname;
      await app.open("/settings/connections");
      await screen.getByRole("button", "Add environment", { exact: true }).tap();
      const dialog = screen.getByRole("dialog");
      await dialog.getByPlaceholder("backend.example.com").fill(host);
      await dialog.getByPlaceholder("PAIRCODE").fill(token);
      await dialog.getByRole("button", "Add environment", { exact: true }).tap();
      await screen.getByRole("button", "List", { exact: true }).tap();
      await screen.getByRole("button", "More actions for Scenario").waitFor({ timeout: 60000 });
      await app.open(path);
      await screen.getByRole("combobox", "Run on", { exact: true }).tap();
      await screen.getByRole("option", "Scenario", { exact: true }).nth(1).tap();
      await screen.getByRole("combobox", /^Branch: (From )?remote-base/).first().waitFor();
      await capture("09-environment-retarget-default");
    } finally { await server.stop(); }
    expect(observations).toEqual({
      "01-global-default-after-add": "New worktree",
      "02-project-file-after-add": "New worktree",
      "04-explicit-choice-after-move": "Current checkout",
      "06-successful-branch-after-default": "Current checkout",
      "06c-initial-branch-choice-after-default": "Current checkout",
      cancelledSend: true,
      "09-environment-retarget-default": "New worktree",
    });
  } finally { await settings(null); }
});
