import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { run } from "./shell.ts";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("An open plain-folder thread notices Git initialization and branch switches", WEB, async ({ t3, app, browser, screen }) => {
  await browser.setViewport({ width: 1280, height: 800 });
  const project = await runPromise(FileSystem.FileSystem.pipe(Effect.flatMap(fs => fs.makeTempDirectory({ directory: "/tmp/factory-pr-47624-evidence-1", prefix: "plain-folder-" }))));
  const added = await runPromise(makeState(T3_HOME).cli(["project", "add", project, "--title", "git-init-demo"]));
  const id = /Added project (\S+) /.exec(added.stdout)?.[1];
  if (!id) throw new Error("Project was not added");
  t3.trackProject(id);
  const thread = await t3.thread({ project, title: "Initialize Git while open", model: "default", messages: ["Hello"] });
  await t3.open("/settings/maintenance");
  await screen.getByRole("combobox", "Background activity profile", { exact: true }).tap();
  await screen.getByRole("option", "Battery saver", { exact: true }).tap();
  await t3.open(thread);
  await screen.getByRole("button", "Initialize Git", { exact: true }).first().waitFor();
  await app.screenshot("plain-folder-before-init");
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
  await git("init", "--initial-branch=main");
  // Observe the open UI without triggering a status refresh; no Git polling runs in Battery saver.
  await runPromise(Effect.sleep("8 seconds"));
  await app.screenshot("open-thread-after-git-init");
  await git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-m", "Initial commit");
  await git("switch", "-c", "topic");
  await runPromise(Effect.sleep("8 seconds"));
  await app.screenshot("open-thread-after-topic-switch");
  await expect(browser.locator('[data-slot="combobox-trigger"][aria-label="Branch: topic"]:visible').first()).toBeVisible({ timeout: 2000 });
  await git("switch", "-c", "second");
  await runPromise(Effect.sleep("3 seconds"));
  await app.screenshot("open-thread-after-second-switch");
  await expect(browser.locator('[data-slot="combobox-trigger"][aria-label="Branch: second"]:visible').first()).toBeVisible({ timeout: 2000 });
});
