/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
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 {
    sourceDefaultGate: { requested: Promise<void>; release: () => Promise<void> };
  }
}

test("A late source workspace default does not overwrite the automatically selected destination", 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, "t3.json": '{"defaultThreadEnvMode":"worktree"}' });
  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);
    await runPromise(run("git", ["branch", "-m", "remote-base"], { cwd: destination }));
    await runPromise(Effect.scoped(Effect.gen(function* () {
      const client = yield* rpcClient(SECOND_HOME, host);
      yield* client["server.updateSettings"]({ patch: { defaultThreadEnvMode: "local" } });
    })));
    await browser.addInitScript(({ source }) => {
      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 === source && 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.sourceDefaultGate = { requested: requested.promise, release: async () => { release(); await replied.promise; } };
      new MutationObserver(() => {
        const input = document.querySelector('input[placeholder="PAIRCODE"]');
        if (input instanceof HTMLInputElement) input.type = "password";
      }).observe(document, { childList: true, subtree: true });
    }, { source });
    const capture = async (label: string) => {
      // Evidence pacing, after the state-specific waits.
      await new Promise((resolve) => setTimeout(resolve, 1500));
      await app.screenshot(label);
    };
    await t3.open();
    await browser.evaluate(async () => { await window.sourceDefaultGate.requested; return null; });
    await screen.getByRole("textbox").fill("Keep the destination workspace");
    await capture("source-workspace-default-read-held");
    await screen.getByRole("button", "Settings", { exact: true }).tap();
    await screen.getByRole("button", "Environments", { exact: true }).tap();
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog", "Add Environment");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByRole("switch", "Automatically balance load").tap();
    await screen.getByRole("button", /^Load balancing/).tap();
    await screen.getByRole("combobox", "Scenario load preference").first().tap();
    await screen.getByRole("option", "Manual only", { exact: true }).tap();
    await capture("pending-source-destination-only-preference");
    await screen.getByRole("dialog", "Settings", { exact: true }).getByRole("button", "Close", { exact: true }).tap();
    const runOn = screen.getByRole("combobox", "Run on", { exact: true });
    await runOn.getByText("Auto balance", { exact: true }).waitFor();
    await runOn.tap();
    await screen.getByRole("option", "Auto balance", { exact: true }).tap();
    await screen.getByRole("combobox", /^Branch: (From )?remote-base/).first().waitFor();
    await capture("destination-while-source-default-is-pending");
    await browser.evaluate(async () => { await window.sourceDefaultGate.release(); return null; });
    await capture("destination-after-late-source-default");
    await expect(screen.getByRole("combobox", "Workspace", { exact: true })).toHaveText("Current checkout");
  } finally { await server.stop(); }
});
