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

import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Uncommitted refreshes when changed files swap at equal totals", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Equal totals", {
    "first.txt": "First original line\n",
    "second.txt": "Second original line\n",
  });
  const start = (model: string) => t3.thread({ project, title: "Equal totals file swap", messages: ["first"], model });
  const thread = await start("showcase").catch((error: unknown) => {
    if (!String(error).includes("Advertised models: default.")) throw error;
    return start("default").catch((discoveryError: unknown) => {
      if (!String(discoveryError).includes("Model default is not advertised")) throw discoveryError;
      return start("showcase");
    });
  });
  const write = (file: string, content: string) => runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.writeFileString(`${project}/${file}`, content);
  }));
  await write("first.txt", "First original line\nAdded first line\n");
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Diff", { exact: true }).tap();
  await screen.getByRole("button", /^Diff scope:/).tap();
  await screen.getByRole("menuitemradio", "Uncommitted", { exact: true }).tap();
  await screen.getByRole("button", "Expand first.txt", { exact: true }).waitFor();
  await browser.mouse.move(1000, 500);
  await app.screenshot("initial-first-file");

  await runPromise(run("git", ["checkout", "--", "first.txt"], { cwd: project }));
  await write("second.txt", "Second original line\nAdded second line\n");
  await screen.getByRole("button", "Toggle thread details panel").tap();
  await screen.getByRole("button", "Git action options").tap();
  await browser.keyboard.press("Escape");
  await browser.keyboard.press("Escape");
  await browser.mouse.move(1000, 500);
  await browser.mouse.down();
  await browser.mouse.up();
  await screen.getByRole("region", "Thread details", { exact: true }).waitFor({ state: "detached" });
  await screen.getByRole("tooltip").waitFor({ state: "detached" });
  await screen.getByText("Toggle thread details (Ctrl+Shift+B)", { exact: true }).waitFor({ state: "detached" });
  try {
    await expect(screen.getByRole("button", "Expand second.txt", { exact: true })).toBeVisible();
  } finally {
    await app.screenshot("after-equal-totals-swap");
  }
});
