import { promises as fs } from "node:fs";
import { randomUUID } from "node:crypto";
import { CommandId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Layout-created worktree with U+2028 in its path is adopted", WEB, async ({ t3, app, screen, browser }) => {
  const name = "api\u2028tools";
  const project = await t3.project("unicode-layout", { "t3.json": JSON.stringify({worktreeLayout: {create: `git -C "$T3_PROJECT_ROOT/${name}" worktree add -q -b "$T3_WORKTREE_BRANCH" "$T3_WORKTREE_PROJECT_PATH/${name}" "$T3_WORKTREE_BASE"`}}) });
  await fs.rename(`${project}/.git`, `${project}-seed-git`);
  const repo = `${project}/${name}`;
  await fs.mkdir(repo);
  await fs.writeFile(`${repo}/README.md`, "Synthetic Unicode worktree example\n");
  const git = (...args: string[]) => runPromise(run("git", args, {cwd: repo}));
  await git("init", "-q", "-b", "main");
  await git("add", ".");
  await git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-qm", "Initial commit");
  await t3.open("/settings/projects");
  await screen.getByText("unicode-layout", {exact: true}).last().tap();
  await screen.getByRole("button", "Approve the create command", {exact: true}).tap();
  await screen.getByRole("button", "Revoke approval of the create command", {exact: true}).waitFor();
  const result = await runPromise(makeState(T3_HOME).cli(["thread", "start", project, "Show the repository status", "--title", "Unicode worktree adoption", "--worktree", "main", "--branch", "feature-ls", "--provider", "devReplay", "--model", "showcase", "--wait", "--json"], [0,1,2]));
  const launched = JSON.parse(result.stdout);
  await t3.open(launched);
  await screen.getByText("Unicode worktree adoption", {exact: true}).first().waitFor();
  await screen.getByRole("textbox").waitFor();
  if (await browser.locator('[aria-label="Dismiss error"]').count()) await screen.getByRole("button", "Dismiss error").first().tap();
  await app.screenshot("unicode-worktree-adoption");
  await expect.poll(async () => (await git("worktree", "list", "--porcelain")).stdout).toContain("branch refs/heads/feature-ls");
  await runPromise(Effect.scoped(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({patch: {storageCleanup: {worktreeOnDelete: true}}});
    yield* client["orchestration.dispatchCommand"]({type: "thread.delete", commandId: CommandId.make(randomUUID()), threadId: ThreadId.make(launched.threadId)});
    const report = yield* client["server.runStorageCleanup"]({});
    console.log("Deletion cleanup report", JSON.stringify(report));
  })));
  await expect.poll(async () => (await git("worktree", "list", "--porcelain")).stdout).not.toContain("branch refs/heads/feature-ls");
  await t3.open("/settings/maintenance");
  await screen.getByRole("button", /^Last run/).tap();
  await screen.getByText("Thread was deleted", {exact: true}).first().waitFor();
  await browser.evaluate(async () => { await Promise.all(document.getAnimations().map((animation) => animation.finished.catch(() => {}))); return true; });
  await app.screenshot("after-thread-and-worktree-removal");
});
