import { execFileSync } from "node:child_process";
import { randomUUID } from "node:crypto";
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();

test("Storage cleanup reports a broken ref and fetches only once for two archived worktrees", WEB, async ({ t3, app, screen, browser }) => {
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const original = await fs.readFile(settingsPath, "utf8");
  const settings = JSON.parse(original);
  await fs.writeFile(settingsPath, JSON.stringify({ ...settings, defaultRuntimeMode: "approval-required", storageCleanup: { ...settings.storageCleanup, worktreeUnchanged: true, worktreeOnMerge: false, worktreeOnDelete: false, worktreeAfterDays: null, worktreeSettledAfterDays: null } }));
  const project = await t3.project("cleanup-demo", { "README.md": "Synthetic cleanup reproduction\n" });
  const remote = `${project}-remote.git`;
  git(project, "clone", "--bare", project, remote);
  git(project, "remote", "add", "origin", remote);
  git(project, "fetch", "origin");
  git(project, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main");
  const threads = [];
  for (const branch of ["feature", "feature-2"]) {
    const thread = await t3.thread({ project, title: branch, messages: ["Show the fixture response"], model: "multi-turn" });
    const worktree = path.join(T3_HOME, "worktrees", "cleanup-demo", branch);
    git(project, "worktree", "add", "-b", branch, worktree, "main");
    threads.push({ ...thread, branch, worktree });
  }
  await runPromise(Effect.scoped(Effect.gen(function* () {
    const rpc = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    for (const thread of threads) {
      yield* rpc["orchestration.dispatchCommand"]({ type: "thread.metadata.update", commandId: randomUUID(), threadId: thread.threadId, branch: thread.branch, worktreePath: thread.worktree });
      yield* rpc["orchestration.dispatchCommand"]({ type: "thread.archive", commandId: randomUUID(), threadId: thread.threadId });
    }
  })));
  // Advance the bare remote without updating this checkout's tracking ref.
  const author = ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid"];
  const next = execFileSync("git", [...author, "commit-tree", "HEAD^{tree}", "-p", "HEAD", "-m", "Remote main advanced"], { cwd: project, encoding: "utf8" }).trim();
  git(project, "push", "origin", `${next}:refs/heads/main`);
  git(project, "update-ref", "refs/remotes/origin/main", "HEAD");
  await fs.copyFile(path.join(project, ".git/refs/remotes/origin/main"), path.join(project, ".git/refs/remotes/origin/main 2"));
  const fetchLog = path.join(T3_HOME, "fetch-invocations.txt");
  const wrapper = path.join(T3_HOME, "count-upload-pack.sh");
  await fs.writeFile(wrapper, `#!/bin/sh\nprintf 'fetch\\n' >> '${fetchLog}'\nexec git-upload-pack "$@"\n`, { mode: 0o755 });
  git(project, "config", "remote.origin.uploadpack", wrapper);
  await t3.open("/settings/maintenance");
  const deleteNow = screen.getByRole("button", "Delete now", { exact: true });
  await deleteNow.waitFor();
  await new Promise(resolve => setTimeout(resolve, 1000));
  await deleteNow.tap();
  await screen.getByRole("button", /^Last run/).waitFor();
  await deleteNow.waitFor();
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().map(animation => animation.finished.catch(() => {})));
  });
  const stable = await app.screenshot("cleanup-stable-check");
  await new Promise(resolve => setTimeout(resolve, 500));
  const capture = await app.screenshot("cleanup-broken-ref-result");
  if (!(await fs.readFile(stable)).equals(await fs.readFile(capture))) throw new Error("Capture was not stable across 500 ms");
  const count = (await fs.readFile(fetchLog, "utf8")).trim().split("\n").length;
  const reasons = await browser.locator("body").textContent();
  const output = process.env.CLEANUP_EVIDENCE_DIR;
  if (output) {
    await fs.mkdir(output, { recursive: true });
    await fs.writeFile(path.join(output, `run-${Date.now()}.json`), JSON.stringify({ fetchInvocations: count, bothWorktreesKept: (await Promise.all(threads.map(t => fs.stat(t.worktree)))).every(s => s.isDirectory()), displayedBrokenRefReason: reasons?.includes("Git found a broken local ref"), displayedGenericReason: reasons?.includes("Git command exited with a non-zero status") }, null, 2));
  }
  expect(count).toBe(1);
  await expect(screen.getByText(/Git found a broken local ref/).first()).toBeVisible();
});
