/// <reference lib="dom" />
import { expect } from "e2e";
import { mkdir, writeFile } from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Busy owners protect discovered and explicitly tracked checkouts", WEB, async ({ t3, app, browser, screen }) => {
  const fixtures = await t3.project("fixtures");
  const cli = (args: string[]) => runPromise(makeState(T3_HOME).cli(args));
  const git = (cwd: string, ...args: string[]) => runPromise(run("git", args, { cwd }));
  const repo = async (name: string) => {
    const cwd = `${fixtures}/${name}`;
    await mkdir(cwd, { recursive: true });
    await git(cwd, "init", "-q", "-b", "main");
    await writeFile(`${cwd}/file.txt`, "main branch content\n");
    await writeFile(`${cwd}/t3.json`, JSON.stringify({ defaultThreadEnvMode: "local" }));
    await writeFile(`${cwd}/.gitignore`, "child/\n");
    await git(cwd, "add", ".");
    await git(cwd, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-qm", "Initial");
    await git(cwd, "switch", "-qc", "other");
    await writeFile(`${cwd}/file.txt`, "other branch content\n");
    await git(cwd, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-qam", "Other");
    await git(cwd, "switch", "-q", "main");
    return cwd;
  };
  const workspace = await repo("workspace");
  const child = await repo("workspace/child");
  const owner = await repo("owner");
  const external = await repo("external");
  for (const args of [[workspace], [child], [owner, "--track", external], [external]]) {
    await cli(["project", "add", ...args]);
  }
  await t3.thread({ project: workspace, title: "Parent workspace agent (working)", messages: ["Work on child"], model: "question" });
  await t3.thread({ project: owner, title: "Owner agent tracking external (working)", messages: ["Work on external"], model: "question" });
  await browser.addInitScript(() => {
    const pending = new Set<string>();
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string") for (const r of [JSON.parse(data)].flat()) {
        if (r?.tag === "vcs.switchRef") { pending.add(String(r.id)); delete document.documentElement.dataset.checkoutDone; }
      }
      return send.call(this, data);
    };
    const add = WebSocket.prototype.addEventListener;
    WebSocket.prototype.addEventListener = function(type, listener, options) {
      if (type === "message" && typeof listener === "function") {
        return add.call(this, type, (event: MessageEvent) => {
          listener.call(this, event);
          if (typeof event.data === "string") for (const r of [JSON.parse(event.data)].flat()) {
            if (r?._tag === "Exit" && pending.delete(String(r.requestId))) document.documentElement.dataset.checkoutDone = "yes";
          }
        }, options);
      }
      return add.call(this, type, listener, options);
    } as typeof WebSocket.prototype.addEventListener;
  });
  const branches: string[] = [];
  for (const [name, cwd] of [["child", child], ["external", external]]) {
    await t3.open("/");
    const projectPicker = browser.locator("[data-draft-project-trigger]");
    await projectPicker.tap();
    await screen.getByRole("option", name, { exact: true }).tap();
    const branch = browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first();
    await branch.click();
    await screen.getByRole("option", /^other\b/).tap();
    await browser.locator('html[data-checkout-done="yes"]').waitFor({ state: "attached" });
    await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible:not([disabled])').first().waitFor();
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().filter((a) => a.effect?.getTiming().iterations !== Infinity).map((a) => a.finished.catch(() => undefined)));
      return null;
    });
    await app.screenshot(`${name}-after-switch-attempt`);
    branches.push((await git(cwd, "branch", "--show-current")).stdout.trim());
  }
  expect(branches).toEqual(["main", "main"]);
});
