/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FS from "node:fs/promises";
import { CommandId, ProjectId, ProviderInstanceId } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Child repositories checked out after thread creation appear in details and diffs", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("platforms", { ".gitignore": "web/\nbackend/\nmobile/\n", "README.md": "Platform workspace\n" });
  const names = ["web", "backend", "mobile"];
  const git = (cwd: string, ...args: string[]) => runPromise(run("git", args, { cwd }));
  for (const name of names) {
    const child = `${project}/${name}`;
    await FS.mkdir(child);
    await FS.writeFile(`${child}/README.md`, `${name}: Original copy\n`);
    await git(child, "init", "--quiet", "--initial-branch=main");
    await git(child, "add", "README.md");
    await git(child, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--quiet", "-m", "Initial copy");
  }
  const { cli } = makeState(T3_HOME);
  const seed = await t3.thread({ project, title: "Setup", messages: ["Start"] });
  const shown = JSON.parse((await runPromise(cli(["thread", "show", seed.threadId, "--json"]))).stdout);
  const launched = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    return yield* client["orchestration.launchThread"]({
      commandId: CommandId.make(crypto.randomUUID()), projectId: ProjectId.make(shown.thread.projectId),
      title: "Update copy across platforms", modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "question" },
      runtimeMode: "full-access", interactionMode: "default",
      workspaceStrategy: { type: "worktree", baseRef: "main", branch: "t3/update-copy-across-platforms", repositories: [] },
    });
  }).pipe(Effect.scoped));
  const thread = { threadId: launched.threadId };
  await runPromise(cli(["thread", "send", thread.threadId, "Start the parent-only thread", "--wait", "--json"], [2]));
  await browser.setViewport({ width: 1920, height: 1080 });
  await t3.open(thread);
  await screen.getByRole("button", /^Strict schemas/).waitFor({ timeout: 90_000 });
  await screen.getByRole("button", /^Strict schemas/).tap();
  await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
  const state = JSON.parse((await runPromise(cli(["thread", "show", thread.threadId, "--json"]))).stdout);
  const cwd = state.thread.worktreePath;
  for (const name of names) await git(`${project}/${name}`, "worktree", "add", "-b", "t3/update-copy-across-platforms", `${cwd}/${name}`, "main");
  await runPromise(cli(["thread", "send", thread.threadId, "Update README copy in web, backend and mobile inside this thread folder", "--wait", "--json"], [2]));
  for (const name of names) await FS.writeFile(`${cwd}/${name}/README.md`, `${name}: Updated copy\n`);
  await screen.getByRole("button", /^Strict schemas/).waitFor({ timeout: 90_000 });
  await screen.getByRole("button", /^Strict schemas/).tap();
  await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Diff", { exact: true }).tap();
  await screen.getByRole("button", /^Diff scope:/).waitFor({ timeout: 60_000 });
  await screen.getByRole("button", /^Diff scope:/).tap();
  await screen.getByRole("menuitemradio", "Latest turn", { exact: true }).tap();
  await screen.getByRole("button", "Diff scope: Latest turn", { exact: true }).waitFor();
  await browser.locator('button[aria-label="Expand backend/README.md"], p:has-text("No net changes in this selection."), p:has-text("No patch available for this selection.")').first().waitFor({ timeout: 60_000 });
  for (const name of ["backend", "mobile", "web"]) {
    const expand = browser.locator(`button[aria-label="Expand ${name}/README.md"]`);
    if (await expand.count()) await expand.click();
  }
  await screen.getByText("Loading code...", { exact: true }).waitFor({ state: "hidden" });
  await app.screenshot("child-repository-diffs");
  for (const name of names) await expect(screen.getByRole("group", `Repository ${name}`, { exact: true })).toBeVisible();
  await expect(screen.getByText("No net changes in this selection.", { exact: true })).not.toBeVisible();
  await app.screenshot("child-repository-diffs-loaded");
});
