/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
import { readFileSync, rmSync, writeFileSync } from "node:fs";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" });
const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

test("Terminal ref changes refresh reftable branch and staged changes promptly", WEB, async ({ t3, app, browser, screen }) => {
  const repo = await t3.project("reftable-demo", { "lib.txt": "one\n" });
  git(repo, "refs", "migrate", "--ref-format=reftable");
  git(repo, "config", "user.name", "Scenario");
  git(repo, "config", "user.email", "scenario@example.invalid");
  git(repo, "config", "core.logAllRefUpdates", "false");
  writeFileSync(`${repo}/lib.txt`, Array.from({ length: 40 }, (_, i) => `${i + 1}\n`).join(""));
  git(repo, "add", "lib.txt");
  git(repo, "commit", "-qm", "Forty lines");
  const linked = await t3.project("linked-reftable-demo");
  rmSync(linked, { recursive: true });
  git(repo, "worktree", "add", "-b", "wt-topic", linked);
  const thread = await t3.thread({ project: repo, title: "Reftable terminal status", messages: ["hello"] });
  const linkedThread = await t3.thread({ project: linked, title: "Linked worktree terminal status", messages: ["hello"] });
  const results: Record<string, boolean> = {};
  for (const [name, cwd, target, initial] of [["repository", repo, thread, "main"], ["linked-worktree", linked, linkedThread, "wt-topic"]] as const) {
    await t3.open(target);
    await screen.getByRole("textbox").waitFor();
    await pause(1500);
    const details = screen.getByRole("region", "Thread details");
    const detailsToggle = screen.getByRole("button", "Toggle thread details panel");
    if ((await detailsToggle.getAttribute("aria-pressed")) !== "true") await detailsToggle.tap();
    await details.waitFor();
    await browser.locator(`[aria-label="Branch: ${initial}"]:visible`).first().waitFor();
    await screen.getByRole("button", "Toggle terminal drawer").tap();
    const terminal = screen.getByLabel("Terminal input");
    for (let i = 0; i < 20; i++) {
      await terminal.focus();
      await browser.keyboard.type(`export PS1='$ '; clear; echo ready > .git-shell-ready`);
      await browser.keyboard.press("Enter");
      await pause(250);
      try { if (readFileSync(`${cwd}/.git-shell-ready`, "utf8").trim() === "ready") break; } catch {}
    }
    // Remove the readiness marker before measuring a clean repository. Refresh by opening anew.
    rmSync(`${cwd}/.git-shell-ready`);
    await t3.open(target);
    await browser.locator(`[aria-label="Branch: ${initial}"]:visible`).first().waitFor();
    await pause(1500);
    const command = async (text: string) => {
      await terminal.focus();
      await browser.keyboard.type(text);
      await browser.keyboard.press("Enter");
      await pause(3000);
    };
    const branch = `${name}-topic`;
    await command(`git switch -c ${branch}`);
    results[`${name} branch`] = await browser.locator(`[aria-label="Branch: ${branch}"]:visible`).first().isVisible();
    await app.screenshot(`${name}-after-switch`);
    // Let the base's periodic refresh settle before testing the independent soft reset.
    await browser.locator(`[aria-label="Branch: ${branch}"]:visible`).first().waitFor({ timeout: 40000 });
    await command("git reset --soft HEAD~1");
    const text = await details.textContent();
    results[`${name} soft reset`] = text.includes("+40") && text.includes("-1") && (await screen.getByRole("button", "Commit", { exact: true }).isVisible());
    await app.screenshot(`${name}-after-soft-reset`);
    // Restore the same clean state via a terminal commit, checking its status independently.
    await screen.getByRole("button", "Commit", { exact: true }).waitFor({ timeout: 40000 });
    await command("git commit -m 'Restore forty lines'");
    results[`${name} commit`] = !(await screen.getByRole("button", "Commit", { exact: true }).isVisible());
    await app.screenshot(`${name}-after-commit`);
  }
  await expect(results).toEqual({ "repository branch": true, "repository soft reset": true, "repository commit": true, "linked-worktree branch": true, "linked-worktree soft reset": true, "linked-worktree commit": true });
});
