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("A hosted side chat commit link selects that commit in the parent Diff", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("demo-repo");
  const git = (...args: string[]) => run("git", args, { cwd: project });
  const sha = await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* git("remote", "add", "origin", "https://github.com/example/demo-repo.git");
    const commit = (subject: string) => git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", subject);
    yield* fs.writeFileString(`${project}/first.txt`, "First committed file\n");
    yield* git("add", "first.txt");
    yield* commit("Add first.txt");
    const { stdout } = yield* git("rev-parse", "HEAD");
    yield* fs.writeFileString(`${project}/second.txt`, "Second committed file\n");
    yield* git("add", "second.txt");
    yield* commit("Add second.txt");
    yield* fs.writeFileString(`${project}/second.txt`, "Second committed file\nUncommitted addition\n");
    yield* fs.writeFileString(`${project}/working-tree.txt`, "Uncommitted new file\n");
    return stdout.trim();
  }));
  const thread = await t3.thread({ project, title: "Main thread", messages: ["Hello"], model: "multi-turn" });
  await t3.open(thread);
  const url = `https://github.com/example/demo-repo/commit/${sha}`;
  const composer = screen.getByRole("textbox", "Message Main thread", { exact: true });
  await composer.fill(`/side Inspect ${url}`);
  await composer.press("Enter");
  const link = screen.getByRole("link", new RegExp(sha.slice(0, 7)));
  await link.waitFor({ timeout: 60_000 });
  await app.screenshot("side-chat-commit-link");
  await link.tap();
  await screen.getByRole("button", /^Diff scope:/).waitFor({ timeout: 30_000 });
  await screen.getByRole("button", /^(Expand|Collapse) (first|second)\.txt$/).waitFor({ timeout: 30_000 });
  try {
    await expect(screen.getByRole("button", "Diff scope: Add first.txt", { exact: true })).toBeVisible({ timeout: 15_000 });
  } finally {
    await app.screenshot("parent-diff-after-commit-click");
  }
});
