import { execFileSync } from "node:child_process";
import { chmodSync, mkdirSync, writeFileSync, existsSync } from "node:fs";
import { randomUUID } from "node:crypto";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Cleanup keeps reporting undeletable git metadata on later sweeps", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("cleanup-demo");
  const started = await runPromise(makeState(T3_HOME).cli(["thread", "start", project, "Hello", "--title", "Metadata cleanup example", "--worktree", "main", "--branch", "feature", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"]));
  const thread = JSON.parse(started.stdout);
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" }).trim();
  const worktree = git("worktree", "list", "--porcelain").split("\n").find(line => line.startsWith("worktree ") && line.slice(9) !== project)!.slice(9);
  const admin = execFileSync("git", ["rev-parse", "--absolute-git-dir"], { cwd: worktree, encoding: "utf8" }).trim();
  const stuck = `${admin}/scratch/c/fanal`;
  mkdirSync(stuck, { recursive: true });
  writeFileSync(`${stuck}/f`, "Synthetic container-owned metadata\n");
  chmodSync(stuck, 0o500);
  try {
    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(thread.threadId) });
      yield* client["server.updateSettings"]({ patch: { storageCleanup: { worktreeUnchanged: true } } });
    }).pipe(Effect.scoped));
    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").scrollIntoView();
    await screen.getByText(/Permission denied/).waitFor();
    await app.screenshot("first-sweep");
    if (existsSync(worktree) || !existsSync(stuck)) throw new Error("Permission failure setup did not delete checkout and leave metadata");
    await cleanup.tap();
    await cleanup.waitFor();
    await browser.locator("#storage-cleanup-last-run").scrollIntoView();
    try {
      await expect(browser.locator("#storage-cleanup-last-run")).toContainText(worktree);
    } finally {
      const dismiss = screen.getByRole("button", "Dismiss notification", { exact: true });
      if (await dismiss.isVisible()) await dismiss.tap();
      await app.screenshot("second-sweep-metadata-remains");
    }
  } finally {
    if (existsSync(stuck)) chmodSync(stuck, 0o700);
  }
});
