import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";

import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test(
  "Repro 43187: a draft moved to another machine takes its default workspace",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const primary = makeState(T3_HOME);
    const second = makeState(SECOND_HOME);
    // Machines share a project through its repository, which needs a remote to be named by.
    const workspace = await runPromise(
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        const path = yield* Path.Path;
        yield* fs.makeDirectory(path.join(T3_HOME, "workspaces"), { recursive: true });
        const directory = yield* fs.makeTempDirectory({
          directory: path.join(T3_HOME, "workspaces"),
          prefix: "demo-",
        });
        yield* fs.writeFileString(path.join(directory, "README.md"), "");
        return directory;
      }),
    );
    const git = (args: ReadonlyArray<string>) => runPromise(run("git", args, { cwd: workspace }));
    await git(["init", "--quiet", "--initial-branch=main"]);
    await git(["remote", "add", "origin", "https://github.com/scenario/demo.git"]);
    await git(["add", "--all"]);
    await git([
      "-c",
      "user.name=Scenario",
      "-c",
      "user.email=scenario@example.invalid",
      "commit",
      "--quiet",
      "--message",
      "Initial commit",
    ]);
    await runPromise(primary.cli(["project", "add", workspace, "--title", "demo"]));
    const server = startSecondServer(app.baseUrl ?? "");
    try {
      const { host, token } = await server.ready;
      await runPromise(second.cli(["project", "add", workspace, "--title", "demo"]));

      await t3.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();
      // The map is the default view; its rows carry no actions menu.
      await screen.getByRole("button", "List", { exact: true }).tap();
      await expect(screen.getByRole("button", "More actions for Scenario")).toBeVisible({
        timeout: 60_000,
      });
      // Destination machine: new threads default to a new worktree from origin.
      const settingsPath = `${T3_HOME}/userdata/settings.json`;
      const fsNode = await import("node:fs");
      const current = JSON.parse(fsNode.readFileSync(settingsPath, "utf8"));
      fsNode.writeFileSync(
        settingsPath,
        JSON.stringify({ ...current, defaultThreadEnvMode: "worktree", newWorktreesStartFromOrigin: true }, null, 2),
      );
      await new Promise((resolve) => setTimeout(resolve, 3000));
      await app.open("/");
      await expect(screen.getByText("Ask anything", { exact: false }).first()).toBeVisible({ timeout: 60_000 });
      await new Promise((resolve) => setTimeout(resolve, 3000));
      await browser.locator('[data-testid="composer-editor"]').focus();
      await browser.keyboard.type("Repro 43187 prompt");
      const workspaceLabel = async () =>
        JSON.stringify({
          current: await browser.locator("text=Current checkout").count(),
          worktree: await browser.locator("text=New worktree").count(),
          url: "",
        });
      console.log("BEFORE_SWITCH", await workspaceLabel());
      await app.screenshot("source-draft");
      const runOn = () => screen.getByText("Scenario").last().tap();
      const machine = (index: number) => browser.locator('[role="menuitemradio"]').nth(index);
      await runOn();
      const items = await browser.locator('[role="menuitemradio"]').allTextContents();
      console.log("RUN_ON_ITEMS", JSON.stringify(items));
      const target = (await machine(0).getAttribute("aria-checked")) === "true" ? 1 : 0;
      await machine(target).click();
      await runOn();
      await expect(machine(target)).toHaveAttribute("aria-checked", "true");
      await browser.keyboard.press("Escape");
      await new Promise((resolve) => setTimeout(resolve, 2000));
      await app.screenshot("after-machine-switch");
      console.log("AFTER_SWITCH", await workspaceLabel());
      await browser.keyboard.press("Escape");
      await browser.locator('[data-testid="composer-editor"]').focus();
      await browser.keyboard.press("Enter");
      await new Promise((resolve) => setTimeout(resolve, 12000));
      await app.screenshot("after-send");
      const listed = await runPromise(second.cli(["thread", "list", "--json", "--project", workspace], [0, 1, 2]));
      console.log("SECOND_THREADS", JSON.stringify(listed));
      const listedPrimary = await runPromise(primary.cli(["thread", "list", "--json", "--project", workspace], [0, 1, 2]));
      console.log("PRIMARY_THREADS", JSON.stringify(listedPrimary));
      const fsN = await import("node:fs");
      const cp = await import("node:child_process");
      const wtDir = `${T3_HOME}/worktrees`;
      console.log("PRIMARY_WORKTREES_DIR", fsN.existsSync(wtDir) ? fsN.readdirSync(wtDir, { recursive: true }).slice(0, 10).join(",") : "none");
      console.log("GIT_WORKTREES", cp.execFileSync("git", ["worktree", "list"], { cwd: workspace }).toString());
    } finally {
      await server.stop();
      await runPromise(primary.cli(["project", "remove", workspace, "--force"]));
    }
  },
);
