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

test("Cleanup removes archived unchanged worktrees with Unicode branch endings", WEB, async ({ t3, app, browser, screen }) => {
  await browser.addInitScript(() => {
    document.addEventListener("DOMContentLoaded", () => {
      const style = document.createElement("style");
      // Privacy mask only: cleanup outcomes and reasons remain untouched.
      style.textContent = "#storage-cleanup-last-run code { filter: blur(7px); user-select: none; }";
      document.head.append(style);
    });
  });
  const { cli } = makeState(T3_HOME);
  const cases = [];
  for (const [name, unicodeProject] of [["Unicode worktree branch", false], ["Unicode project branch", true]] as const) {
    const project = await t3.project(unicodeProject ? "project-branch" : "worktree-branch");
    const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
    if (unicodeProject) await git("branch", "-m", "main", "trunk\u3000");
    const started = await runPromise(cli(["thread", "start", project, "Hello", "--title", name, "--worktree", unicodeProject ? "trunk\u3000" : "main", "--branch", unicodeProject ? "featureb" : "feature", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"]));
    const { threadId } = JSON.parse(started.stdout);
    const shown = await runPromise(cli(["thread", "show", threadId, "--json"]));
    const { thread } = JSON.parse(shown.stdout);
    if (!unicodeProject) await runPromise(run("git", ["branch", "-m", "feature\u3000"], { cwd: thread.worktreePath }));
    cases.push({ threadId, worktreePath: thread.worktreePath });
  }
  for (const item of cases) {
    await t3.open(item);
    await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').waitFor({ timeout: 60000 });
    if (item === cases[0]) await browser.locator('[aria-label="Branch: feature　"]:visible').waitFor({ timeout: 60000 });
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["orchestration.dispatchCommand"]({ type: "thread.archive", commandId: CommandId.make(randomUUID()), threadId: ThreadId.make(item.threadId) });
    }).pipe(Effect.scoped));
  }
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  await fs.writeFile(settingsPath, JSON.stringify({ ...settings, storageCleanup: { ...settings.storageCleanup, worktreeUnchanged: true } }));
  await t3.open("/settings/maintenance");
  const cleanup = screen.getByRole("button", "Delete now", { exact: true });
  await screen.getByRole("button", /^Last run/).tap();
  await browser.locator("#storage-cleanup-last-run").waitFor();
  await browser.locator("#storage-cleanup-last-run").scrollIntoView();
  await app.screenshot("first-cleanup-results");
  await cleanup.tap();
  await screen.getByRole("button", "Deleting…", { exact: true }).waitFor({ state: "hidden" });
  await cleanup.tap();
  await screen.getByRole("button", "Deleting…", { exact: true }).waitFor({ state: "hidden" });
  await cleanup.tap();
  await screen.getByRole("button", "Deleting…", { exact: true }).waitFor({ state: "hidden" });
  await browser.locator("#storage-cleanup-last-run").scrollIntoView();
  await app.screenshot("unicode-branch-cleanup-results");
  const remaining = await Promise.all(cases.map(async item => fs.access(item.worktreePath).then(() => true, () => false)));
  expect(remaining).toEqual([false, false]);
});
