import { expect } from "e2e";
import { readFile, writeFile, access } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

test("cleanup follows an unobserved idle worktree branch rename", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Cleanup demo", { "README.md": "Synthetic cleanup demonstration\n" });
  const control = await t3.thread({ project, title: "Control", messages: ["go"] });
  const { cli } = makeState(T3_HOME);
  const launch = await runPromise(cli(["thread", "start", project, "go", "--title", "Idle worktree", "--provider", "devReplay", "--model", "multi-turn", "--worktree", "main", "--branch", "feature/two", "--wait", "--json"]));
  const thread = JSON.parse(launch.stdout);
  const show = async () => JSON.parse((await runPromise(cli(["thread", "show", thread.threadId, "--json"]))).stdout).thread;
  const initial = await show();
  await t3.open(control);
  const row = browser.locator(`[data-thread-item$="${thread.threadId}"]`);
  await row.hover();
  await row.getByRole("button", "Settle thread").tap();
  await browser.goto("about:blank");
  await wait(2000);
  execFileSync("git", ["branch", "-m", "fix/thing-two"], { cwd: initial.worktreePath });
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const sweep = async (days: number) => {
    const settings = JSON.parse(await readFile(settingsPath, "utf8"));
    settings.storageCleanup = { ...settings.storageCleanup, worktreeUnchanged: true, logsAfterDays: days };
    await writeFile(settingsPath, JSON.stringify(settings));
    await wait(5000);
  };
  await wait(65000);
  await sweep(30);
  console.log("After sweep 1 saved branch:", (await show()).branch);
  await wait(65000);
  await sweep(31);
  const final = await show();
  let exists = true;
  try { await access(initial.worktreePath); } catch { exists = false; }
  console.log("After sweep 2:", JSON.stringify({ branch: final.branch, worktreeExists: exists }));
  await t3.open("/settings/maintenance");
  await screen.getByRole("button", "Last run", { exact: false }).tap();
  await screen.getByText("Idle worktree", { exact: true }).waitFor({ state: "visible" });
  await wait(700);
  // Hide generated filesystem locations in public captures; cleanup results stay untouched.
  await browser.evaluate(() => {
    for (const code of document.querySelectorAll("code")) {
      if (code.textContent?.startsWith("/")) code.textContent = "[synthetic workspace]";
    }
  });
  await app.screenshot("cleanup-report-stable");
  await wait(500);
  await app.screenshot("cleanup-after-two-unobserved-sweeps");
  expect(exists).toBe(false);
});
