/// <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";

test(
  "Automatic machine selection uses the chosen project's workspace default",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const repository = {
      ".git/config": '[remote "origin"]\n\turl = https://github.com/scenario/demo.git\n',
    };
    const sourceProject = await t3.project("demo", repository);
    const second = makeState(SECOND_HOME);
    const server = startSecondServer(app.baseUrl ?? "");
    try {
      const { host, token } = await server.ready;
      const remoteProject = await second.state.project("demo", repository);
      await runPromise(run("git", ["branch", "-m", "remote-base"], { cwd: remoteProject }));
      const localOrigin = `${remoteProject}/../origin.git`;
      await runPromise(run("git", ["clone", "--bare", remoteProject, localOrigin]));
      for (const cwd of [sourceProject, remoteProject]) {
        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(SECOND_HOME, host);
            yield* client["server.updateSettings"]({ patch: { defaultThreadEnvMode: "worktree" } });
          }),
        ),
      );

      await browser.addInitScript(({ paths }) => {
        const redact = () => {
          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 ?? "";
            let next = old;
            for (const path of paths) next = next.replaceAll(path, "[synthetic repository]");
            if (next !== old) node.textContent = next;
          }
        };
        new MutationObserver(redact).observe(document, { childList: true, subtree: true, characterData: true });
      }, { paths: [sourceProject, remoteProject, localOrigin] });
      const capture = async (label: string) => {
        // Pause only to make each interaction readable in the evidence recording.
        await new Promise((resolve) => setTimeout(resolve, 1500));
        await app.screenshot(label);
      };
      await t3.open();
      const workspace = screen.getByRole("combobox", "Workspace", { exact: true });
      await workspace.getByText("Current checkout").waitFor({ timeout: 60_000 });
      await screen.getByRole("textbox").fill("Plan the next change");
      await capture("source-draft-current-checkout");
      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 dialog.getByPlaceholder("PAIRCODE").fill(token);
      await dialog.getByRole("button", "Add environment").tap();

      await capture("two-paired-machines");
      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("destination-only-load-preference");
      await app.open(draftPath);
      const runOn = screen.getByRole("combobox", "Run on", { exact: true });
      await runOn.getByText("Auto balance", { exact: true }).waitFor({ timeout: 60_000 });
      await screen
        .getByRole("combobox", /^Branch: (From )?remote-base/)
        .first()
        .waitFor({ timeout: 60_000 });
      await capture("workspace-after-auto-machine-selection");
      const observedWorkspace = await browser.evaluate(() => document.querySelector('[role="combobox"][aria-label="Workspace"]')?.textContent?.trim() ?? "");
      // Continue through sending on both commits before checking the routing difference.
      await runOn.tap();
      await screen.getByRole("option", "Scenario", { exact: true }).last().tap();
      await workspace.getByText("New worktree").waitFor();
      await capture("manual-destination-workspace-control");
      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");
      await screen.getByRole("textbox").press("Enter");
      await screen.getByText("first fixture turn complete", { exact: false }).waitFor({ timeout: 60_000 });
      await capture("manual-destination-send-control");

      const preferences = async (source: string, destination: 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", source, { exact: true }).tap();
        await choices.last().tap();
        await screen.getByRole("option", destination, { exact: true }).tap();
        await capture("load-preferences-" + source.toLowerCase().replaceAll(" ", "-"));
      };
      await runPromise(run("git", ["branch", "-m", "source-only"], { cwd: sourceProject }));
      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 preferences("Normal", "Manual only");
      await t3.open();
      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("Send-time destination worktree proof");
      await runOn.getByText("Auto balance", { exact: true }).waitFor();
      await screen.getByRole("combobox", /^Branch: (From )?source-only/).first().waitFor();
      const sendDraft = new URL(await browser.url()).pathname;
      await capture("send-time-source-only");
      await preferences("Manual only", "Normal");
      await app.open(sendDraft);
      await screen.getByRole("combobox", /^Branch: (From )?source-only/).first().waitFor();
      await capture("before-send-refresh-source-only");
      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");
      await screen.getByRole("textbox").press("Enter");
      await screen.getByText(/first fixture turn complete|Workspace preparation failed during|Base ref/).first().waitFor({ timeout: 60_000 });
      await capture("after-send-refresh-destination");
      const worktreeSendSucceeded = await browser.evaluate(() => document.body.textContent?.includes("first fixture turn complete") ?? false);
      await runPromise(Effect.scoped(Effect.gen(function* () {
        const client = yield* rpcClient(SECOND_HOME, host);
        yield* client["server.updateSettings"]({ patch: { defaultThreadEnvMode: "local" } });
      })));
      await preferences("Normal", "Manual only");
      await t3.open();
      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("Send-time Current checkout proof");
      await screen.getByRole("combobox", /^Branch: (From )?source-only/).first().waitFor();
      const checkoutDraft = new URL(await browser.url()).pathname;
      await capture("current-checkout-source-only-before-routing");
      await preferences("Manual only", "Normal");
      await app.open(checkoutDraft);
      await screen.getByRole("combobox", /^Branch: (From )?source-only/).first().waitFor();
      await capture("current-checkout-before-send-refresh");
      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");
      await screen.getByRole("textbox").press("Enter");
      await screen.getByText(/first fixture turn complete|Workspace preparation failed during|Base ref/).first().waitFor({ timeout: 60_000 });
      await capture("current-checkout-after-send-refresh");
      await expect(observedWorkspace).toBe("New worktree");
      await expect(worktreeSendSucceeded).toBe(true);
      await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeVisible();
    } finally {
      await server.stop();
    }
  },
);
