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(
  "A new draft keeps its selected models when it moves to another machine",
  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();
      await screen.getByRole("button", "More actions for Scenario Two").waitFor({ state: "visible", timeout: 60_000 });
      await app.open("/");
      const prompt = "Compare the implementation and propose a small improvement.";
      const editor = browser.locator('[contenteditable="true"]').first();
      // The worktree mode leaves the unsent draft free to move between project copies.
      await screen.getByRole("button", "Current checkout", { exact: false }).first().tap();
      await screen.getByText("New worktree", { exact: true }).tap();
      await screen.getByRole("combobox", "Run on").tap();
      await screen.getByRole("option", "Scenario", { exact: true }).tap();
      await editor.fill(prompt);
      const picker = () => browser.locator('button[data-composer-shortcut~="composer.effort"]').first();
      const addModel = async (name: string) => {
        await picker().click();
        await browser.keyboard.type(name);
        await browser.keyboard.press("Shift+Enter");
        await browser.keyboard.press("Escape");
        await browser.keyboard.press("Escape");
        await browser.locator('[data-model-picker-content]').waitFor({ state: "hidden" });
      };
      await addModel("Plan and reads");
      const screenshot = async (label: string) => {
        await browser.evaluate(async () => {
          await Promise.all(document.getAnimations()
            .filter((animation) => animation.effect?.getComputedTiming().iterations !== Infinity)
            .map((animation) => animation.finished.catch(() => {})));
        });
        await app.screenshot(label);
      };
      const snapshots: Array<{ stage: string; models: string | null; prompt: string }> = [];
      const capture = async (stage: string) => {
        snapshots.push({ stage, models: await picker().getAttribute("aria-label"), prompt: await editor.textContent() });
        await screenshot(stage);
        // Show the complete checked model names as well as the unobscured prompt.
        await picker().click();
        await screen.getByPlaceholder("Search models...").fill("");
        await screenshot(`${stage}-models`);
        await browser.keyboard.press("Escape");
        await browser.locator('[data-model-picker-content]').waitFor({ state: "hidden" });
      };
      await capture("before-machine-switch");
      const runOn = () => screen.getByRole("combobox", "Run on").tap();
      await runOn();
      await screen.getByRole("option", "Scenario Two", { exact: true }).tap();
      await capture("after-machine-switch");
      await addModel("Question");
      await capture("changed-selections-on-second-machine");
      await runOn();
      await screen.getByRole("option", "Scenario", { exact: true }).tap();
      await capture("after-switch-back");

      // Configure eligibility while the manually routed draft cannot auto-move.
      await screen.getByRole("button", "Settings", { exact: true }).tap();
      await screen.getByRole("button", "Environments", { exact: true }).tap();
      await screen.getByRole("switch", "Automatically balance load").tap();
      await screen.getByText("Load balancing", { exact: true }).tap();
      await screen.getByRole("combobox", "Scenario load preference", { exact: true }).tap();
      await screen.getByRole("option", "Manual only", { exact: true }).tap();
      await screen.getByRole("switch", "Automatically balance load").tap();
      await screen.getByRole("button", "Close", { exact: true }).tap();

      // This draft has never manually picked a machine. Its first automatic choice
      // happens after selecting models, with only Scenario Two eligible.
      await screen.getByRole("button", "New thread", { exact: true }).tap();
      await editor.fill(prompt);
      await addModel("Plan and reads");
      await capture("before-initial-automatic-routing");
      await screen.getByRole("button", "Settings", { exact: true }).tap();
      await screen.getByRole("button", "Environments", { exact: true }).tap();
      await screen.getByRole("switch", "Automatically balance load").tap();
      await screenshot("automatic-routing-preferences");
      await screen.getByRole("button", "Close", { exact: true }).tap();
      // Capture the automatic mode separately from the complete model list.
      await runOn();
      await screenshot("initial-automatic-routing-machine");
      await browser.keyboard.press("Escape");
      await capture("after-initial-automatic-routing");
      expect(snapshots).toEqual([
        { stage: "before-machine-switch", models: expect.stringContaining("Showcase, Plan and reads"), prompt },
        { stage: "after-machine-switch", models: expect.stringContaining("Showcase, Plan and reads"), prompt },
        { stage: "changed-selections-on-second-machine", models: expect.stringContaining("Showcase, Plan and reads, Question"), prompt },
        { stage: "after-switch-back", models: expect.stringContaining("Showcase, Plan and reads, Question"), prompt },
        { stage: "before-initial-automatic-routing", models: expect.stringContaining("Showcase, Plan and reads"), prompt },
        { stage: "after-initial-automatic-routing", models: expect.stringContaining("Showcase, Plan and reads"), prompt },
      ]);

    } finally {
      await server.stop();
      await runPromise(primary.cli(["project", "remove", workspace, "--force"]));
    }
  },
);
