import { expect } from "e2e";
import { mkdtempSync, writeFileSync, readFileSync, mkdirSync, existsSync } from "node:fs";
import { join } from "node:path";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Cleanup removes an idle worktree with a published tag-only submodule release", WEB, async ({t3, app, screen, browser}) => {
  // Redact synthetic filesystem locations from the public recording.
  await browser.addInitScript(() => {
    document.addEventListener("DOMContentLoaded", () => {
      const style = document.createElement("style");
      style.textContent = "#storage-cleanup-last-run code { visibility: hidden !important; }";
      document.head.append(style);
    });
  });
  const scratch = process.env.SCENARIO_SCRATCH!;
  const fixture = mkdtempSync(join(scratch, "fixture-"));
  const project = await t3.project("tagged-submodule");
  const git = async (cwd: string, ...args: string[]) => (await runPromise(run("git", ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", ...args], {cwd}))).stdout.trim();
  const upstream = join(fixture, "release-upstream");
  mkdirSync(upstream);
  await git(upstream, "init", "-b", "main");
  writeFileSync(join(upstream, "library.txt"), "Published library\n");
  await git(upstream, "add", ".");
  await git(upstream, "commit", "-m", "Published main");
  const tree = await git(upstream, "rev-parse", "HEAD^{tree}");
  const release = await git(upstream, "commit-tree", tree, "-p", "HEAD", "-m", "Tag-only release");
  await git(upstream, "tag", "v0.9.1-ea2", release);
  await git(project, "-c", "protocol.file.allow=always", "submodule", "add", upstream, "library");
  await git(join(project, "library"), "checkout", "--detach", "v0.9.1-ea2");
  await git(project, "add", ".");
  await git(project, "commit", "-m", "Pin published submodule release");
  const parentRemote = join(fixture, "project-remote.git");
  await git(fixture, "clone", "--bare", project, parentRemote);
  await git(project, "remote", "add", "origin", parentRemote);
  await git(project, "fetch", "origin");
  const launched = await runPromise(run(process.execPath, ["apps/server/src/bin.ts", "thread", "start", project, "first", "--title", "Published submodule release", "--worktree", "main", "--branch", "cleanup-tag-release", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json", "--base-dir", T3_HOME], {cwd: APP_DIR, env: {PATH: process.env.PATH, HOME: process.env.HOME}}));
  const thread = JSON.parse(launched.stdout);
  const worktrees = await git(project, "worktree", "list", "--porcelain");
  const worktree = worktrees.split("\n").find(line => line.startsWith("worktree ") && line.slice(9) !== project)!.slice(9);
  await git(worktree, "-c", "protocol.file.allow=always", "submodule", "update", "--init");
  const module = join(worktree, "library");
  await git(module, "fetch", "origin", "tag", "v0.9.1-ea2");
  if (await git(module, "branch", "-r", "--contains", release)) throw new Error("Fixture release unexpectedly belongs to a remote branch");
  if (await git(worktree, "status", "--porcelain")) throw new Error("Fixture worktree is dirty");
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", {exact:true}).waitFor({state:"visible"});
  // Restart closes the idle replay process; the next message would create a new session.
  await browser.keyboard.press("Control+k");
  await screen.getByPlaceholder("Search commands, projects, and threads...").fill("Restart agent session");
  await screen.getByText("Restart agent session", {exact:true}).tap();
  await screen.getByText("Agent session will restart", {exact:true}).waitFor({state:"visible"});
  await t3.open("/settings/maintenance");
  const settingsPath = join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(readFileSync(settingsPath, "utf8"));
  writeFileSync(settingsPath, JSON.stringify({...settings, storageCleanup: {...settings.storageCleanup, worktreeAfterDays: 1}}));
  await screen.getByRole("button", "Last run", {exact: false}).tap();
  await screen.getByText("Inactive for 0 of 1 days", {exact: false}).waitFor({state: "visible", timeout: 60000});
  writeFileSync(process.env.SCENARIO_CLOCK_FILE!, String(2 * 86400000));
  await screen.getByRole("button", "Delete now", {exact: true}).tap();
  await screen.getByRole("button", "Delete now", {exact: true}).waitFor({state:"visible"});
  await screen.getByText(/Submodule has commits not on a remote-tracking ref|Inactive for 2 days/).waitFor({state:"visible", timeout:60000});
  // Both outcomes are visible in the real cleanup report before the differential assertion.
  await browser.evaluate(() => document.querySelector("#storage-cleanup-last-run")?.scrollIntoView({block:"center"}));
  await app.screenshot("cleanup-result");
  await expect.poll(() => existsSync(worktree)).toBe(false);
});
