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

const branch = "t3/fix-antigravity-model-tagging";
const prHead = "311c7c0369d2b18c5153f2b94c38fc1977bd0ac4";
test("Cleanup removes the fork's squash-merged worktree with an upstream remote", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Merged fork worktree");
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
  await git("fetch", APP_DIR, "refs/remotes/origin/main:refs/remotes/origin/main", prHead);
  await git("reset", "--hard", "origin/main");
  await git("remote", "add", "origin", "https://github.com/pingdotgg/t3code.git");
  await git("remote", "add", "upstream", "https://github.com/cli/cli.git");
  await git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main");
  await git("update-ref", `refs/remotes/origin/${branch}`, prHead);
  const started = await runPromise(makeState(T3_HOME).cli(["thread", "start", project, "Start", "--title", "Merged PR cleanup", "--provider", "devReplay", "--model", "showcase", "--worktree", prHead, "--branch", branch, "--wait", "--json"]));
  const { threadId } = JSON.parse(started.stdout);
  await git("branch", "--set-upstream-to", `origin/${branch}`, branch);
  await runPromise(Effect.scoped(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client["orchestration.dispatchCommand"]({ type: "thread.settle", commandId: CommandId.make(randomUUID()), threadId: ThreadId.make(threadId) });
  })));
  await t3.open("/settings/worktrees");
  await screen.getByRole("switch", "Delete merged worktrees", { exact: true }).tap();
  // Enabling the rule sweeps within the settle-script grace; the manual run follows it.
  await delay(65_000);
  await t3.open("/settings/maintenance");
  await browser.evaluate(() => {
    const style = document.createElement("style");
    style.textContent = '#storage-cleanup-last-run code, #storage-cleanup-last-run span:has(+ code) { display: none; }';
    document.head.append(style);
  });
  await screen.getByRole("button", "Delete now", { exact: true }).tap();
  await screen.getByRole("button", "Delete now", { exact: true }).waitFor();
  await screen.getByRole("button", /^Last run/).tap();
  await screen.getByText(/^(Not merged|Pull request was merged)$/).waitFor();
  await delay(1_000);
  try {
    await expect(screen.getByText("Pull request was merged", { exact: true })).toBeVisible();
  } finally {
    await app.screenshot("merged-worktree-cleanup");
    await delay(2_000);
  }
});
