/// <reference lib="dom" />
import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
import { join, dirname } from "node:path";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

const git = (cwd: string, ...args: string[]) => execFileSync("git", ["-c", "protocol.file.allow=always", "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", ...args], { cwd, encoding: "utf8" }).trim();

test("Cleanup keeps untracked and ignored files when submodule inspection retains the worktree", WEB, async ({ t3, app, screen, browser }) => {
  await browser.addInitScript(() => {
    const hideFixturePaths = () => {
      for (const element of document.querySelectorAll("code")) {
        if (element.textContent?.startsWith("/")) element.textContent = "[disposable fixture path hidden]";
      }
    };
    new MutationObserver(hideFixturePaths).observe(document, { childList: true, subtree: true });
  });
  const project = await t3.project("demo", { ".gitignore": ".env\n", "README.md": "Disposable submodule cleanup reproduction\n" });
  const root = dirname(project);
  for (const name of ["child", "module"]) {
    const path = join(root, name);
    mkdirSync(path);
    git(path, "init", "-b", "main");
    writeFileSync(join(path, "README.md"), `${name}\n`);
    git(path, "add", "."); git(path, "commit", "-m", "Initial fixture");
    if (name === "module") {
      git(path, "submodule", "add", join(root, "child.git"), "child");
      git(path, "commit", "-am", "Add nested child");
    }
    git(root, "clone", "--bare", path, join(root, `${name}.git`));
  }
  git(project, "submodule", "add", join(root, "module.git"), "module");
  git(project, "commit", "-am", "Add module");
  git(root, "clone", "--bare", project, join(root, "demo.git"));
  git(project, "remote", "add", "origin", join(root, "demo.git"));
  const { cli } = makeState(T3_HOME);
  const started = await runPromise(cli(["thread", "start", project, "first", "--title", "Submodule cleanup", "--provider", "devReplay", "--model", "multi-turn", "--worktree", "main", "--branch", "feature/submodule-demo", "--wait", "--json"]));
  const thread = JSON.parse(started.stdout);
  const worktrees = git(project, "worktree", "list", "--porcelain").split("\n\n");
  const worktree = worktrees.find((entry) => entry.includes("branch refs/heads/feature/submodule-demo"))!.split("\n")[0]!.slice(9);
  git(worktree, "submodule", "update", "--init", "--recursive");
  const childGit = git(join(worktree, "module/child"), "rev-parse", "--absolute-git-dir");
  git(join(worktree, "module"), "submodule", "deinit", "child");
  writeFileSync(join(childGit, "HEAD"), "not a ref\n");
  writeFileSync(join(worktree, "notes.txt"), "my notes\n");
  writeFileSync(join(worktree, ".env"), "DEMO_ONLY=yes\n");
  await t3.open(thread);
  await t3.open("/settings/worktrees");
  await screen.getByRole("button", "Advanced", { exact: true }).last().tap();
  await screen.getByRole("switch", "Delete settled worktrees", { exact: true }).tap();
  await screen.getByRole("textbox", "Delete settled worktrees in days").fill("0");
  await browser.keyboard.press("Enter");
  await screen.getByRole("combobox", "Keep worktrees with local changes").tap();
  await screen.getByRole("option", "Edited tracked files").tap();
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).first().waitFor({ state: "visible" });
  await browser.keyboard.press("ControlOrMeta+Shift+s");
  await screen.getByRole("button", "Un-settle thread", { exact: true }).first().waitFor({ state: "attached", timeout: 15_000 });
  // The real cleanup service deliberately gives settle scripts a 60 second grace period.
  await new Promise((resolve) => setTimeout(resolve, 62_000));
  await t3.open("/settings/maintenance");
  const filesBefore = { notes: existsSync(join(worktree, "notes.txt")), env: existsSync(join(worktree, ".env")) };
  await screen.getByRole("button", "Delete now", { exact: true }).tap();
  await screen.getByText("0 removed, 1 kept", { exact: false }).first().waitFor({ state: "visible" });
  await screen.getByRole("button", "Last run", { exact: false }).tap();
  await screen.getByText("Submodules could not be inspected", { exact: false }).first().waitFor({ state: "visible" });
  await screen.getByText("Submodules could not be inspected", { exact: false }).first().scrollIntoView();
  const filesAfter = {
    worktree: existsSync(worktree),
    notes: existsSync(join(worktree, "notes.txt")) ? readFileSync(join(worktree, "notes.txt"), "utf8") : null,
    env: existsSync(join(worktree, ".env")) ? readFileSync(join(worktree, ".env"), "utf8") : null,
  };
  await browser.evaluate(({ before, after }) => {
    const panel = document.createElement("aside");
    panel.style.cssText = "position:fixed;bottom:20px;right:20px;width:560px;padding:20px;background:#111827;color:#f9fafb;border:2px solid #94a3b8;border-radius:8px;z-index:99999;font:16px/1.6 monospace;white-space:pre-wrap";
    panel.textContent = `Filesystem verification — scenario driver\nBefore Delete now: notes.txt ${before.notes ? "present" : "MISSING"}; .env ${before.env ? "present" : "MISSING"}\nAfter Delete now:\n  worktree folder: ${after.worktree ? "retained" : "MISSING"}\n  notes.txt: ${after.notes === null ? "DELETED" : JSON.stringify(after.notes.trim())}\n  .env: ${after.env === null ? "DELETED" : JSON.stringify(after.env.trim())}`;
    document.body.append(panel);
  }, { before: filesBefore, after: filesAfter });
  await app.screenshot("kept-worktree-files");
  expect(filesAfter).toEqual({ worktree: true, notes: "my notes\n", env: "DEMO_ONLY=yes\n" });
});
