import { execFileSync } from "node:child_process";
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
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 { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const scratch = "/tmp/cleanup-proof";
const trace = `${scratch}/git-trace.json`;
const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8", env: { ...process.env, GIT_TRACE2_EVENT: undefined } }).trim();

test("Cleanup scans local changes only after removal eligibility", WEB, async ({ t3, app, screen, browser }) => {
  const files = Object.fromEntries(Array.from({ length: 20000 }, (_, i) => [`files/file-${i}.txt`, `tracked ${i}\n`]));
  const project = await t3.project("cleanup-demo", files);
  const origin = `${project}-origin.git`;
  git(project, "init", "--bare", "--initial-branch=main", origin);
  git(project, "remote", "add", "origin", origin);
  git(project, "push", "-u", "origin", "main");
  const launched = await runPromise(makeState(T3_HOME).cli(["thread", "start", project, "first", "--title", "Retained feature", "--provider", "devReplay", "--model", "multi-turn", "--worktree", "main", "--branch", "feature-retained", "--wait", "--json"]));
  const { threadId } = JSON.parse(launched.stdout);
  const listing = git(project, "worktree", "list", "--porcelain").split("\n\n");
  const worktree = listing.find(block => block.includes("branch refs/heads/feature-retained"))!.split("\n")[0]!.slice(9);
  writeFileSync(`${worktree}/retained.txt`, "Unmerged feature commit\n");
  git(worktree, "add", "retained.txt");
  git(worktree, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Retained feature commit");
  const rpc = <A>(call: (client: any) => Effect.Effect<A, any, any>) => runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    return yield* call(client);
  }).pipe(Effect.scoped)) as Promise<A>;
  await rpc(client => client["orchestration.dispatchCommand"]({ type: "thread.archive", commandId: CommandId.make(crypto.randomUUID()), threadId: ThreadId.make(threadId) }));
  await rpc(client => client["server.updateSettings"]({ patch: { storageCleanup: { worktreeOnMerge: true, worktreeUnchanged: true, worktreeOnDelete: false, worktreeAfterDays: null, worktreeSettledAfterDays: null, logsAfterDays: null, browserArtifactsAfterDays: null } } }));
  // Drain the automatic sweep caused by the settings change before recording manual sweeps.
  await rpc(client => client["server.runStorageCleanup"]({}));
  await t3.open("/settings/maintenance");
  await browser.evaluate(() => { const style = document.createElement("style"); style.textContent = "*,*::before,*::after { animation: none !important; transition: none !important; } #storage-cleanup-last-run code { visibility: hidden !important; }"; document.head.appendChild(style); });
  await screen.getByRole("button", /^Last run/).tap();
  const sha = git(APP_DIR, "rev-parse", "HEAD");
  const out = `${scratch}/${sha.slice(0, 10)}-${Date.now()}`;
  mkdirSync(out, { recursive: true });
  const observations: any[] = [];
  async function sweep(label: string) {
    const offset = readFileSync(trace, "utf8").length;
    const report: any = await rpc(client => client["server.runStorageCleanup"]({}));
    const events = readFileSync(trace, "utf8").slice(offset).trim().split("\n").filter(Boolean).map(line => JSON.parse(line));
    const sessions = new Set(events.filter(e => e.event === "def_repo" && e.worktree === worktree).map(e => e.sid));
    const commands = events.filter(e => e.event === "start" && sessions.has(e.sid)).map(e => e.argv.join(" ").replaceAll(worktree, "<worktree>").replaceAll(origin, "<bare-origin>").replaceAll(project, "<project>").replaceAll(T3_HOME, "<isolated-home>"));
    const fullStatuses = commands.filter(command => command.includes("status --porcelain=v1 -z") && command.includes("--untracked-files=all"));
    const entry = report.entries.find((entry: any) => entry.threadId === threadId);
    observations.push({ label, outcome: entry?.outcome, reason: entry?.reason, fullStatusCount: fullStatuses.length, commands });
    await screen.getByText(entry.reason, { exact: true }).waitFor();
    await app.screenshot(label);
  }
  await sweep("unmerged-clean");
  writeFileSync(`${worktree}/files/file-0.txt`, "Uncommitted edit\n");
  await sweep("unmerged-dirty");
  git(project, "merge", "--ff-only", "feature-retained");
  git(project, "push", "origin", "main");
  await sweep("eligible-dirty-protected");
  writeFileSync(`${out}/transcript.json`, JSON.stringify({ sha, trackedFiles: 20000, environment: "Linux; real dev server; Chromium 1280x800; isolated synthetic data; cleanup invoked through the same WebSocket RPC as Delete now", observations }, null, 2));
  console.log(`PUBLIC_TRANSCRIPT ${out}/transcript.json`);
  expect(observations.slice(0, 2).map(o => o.fullStatusCount)).toEqual([0, 0]);
});
