import { expect } from "e2e";
import { writeFileSync, existsSync, watch, readFileSync, globSync, statSync } from "node:fs";
import { basename, join } from "node:path";
import * as Effect from "effect/Effect";
import { DEFAULT_TERMINAL_ID, ThreadId } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("An external checkout switch stops commit on new branch", WEB, async ({t3, app, screen, browser}) => {
  const results: boolean[] = [];
  const stableScreenshot = async (label: string) => {
    const read = (file: string) => {
      if (existsSync(file)) return readFileSync(file);
      const root = ".e2e/prove";
      const matches = globSync(`**/${basename(file)}`, {cwd:root}).map(p => join(root,p));
      matches.sort((a,b) => statSync(b).mtimeMs-statSync(a).mtimeMs);
      return readFileSync(matches[0]!);
    };
    await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 600)));
    for (let attempt=0; attempt<4; attempt++) {
      const first = await app.screenshot(`${label}-stability-check`);
      await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 500)));
      const second = await app.screenshot(`${label}-candidate`);
      if (read(first).equals(read(second))) { await app.screenshot(label); return; }
    }
    throw new Error(`Capture did not settle: ${label}`);
  };
  for (const detached of [false, true]) {
    const label = detached ? "detached" : "named-branch";
    const project = await t3.project(`demo-${label}`, {"README.md": "Demo\n"});
    const git = (...args: string[]) => runPromise(run("git", args, {cwd: project}));
    await git("config", "user.name", "Scenario");
    await git("config", "user.email", "scenario@example.invalid");
    await git("switch", "-c", "terminal-work");
    await git("commit", "--allow-empty", "-m", "Unrelated branch commit");
    await git("switch", "main");
    if (detached) await git("switch", "--detach", "main");
    const input = {project, title: `Commit work (${label})`, messages: ["Start"]};
    const thread = await t3.thread({...input, model:"default"}).catch(() => t3.thread(input));
    writeFileSync(`${project}/README.md`, "Demo\nA local edit\n");
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["terminal.open"]({threadId: ThreadId.make(thread.threadId), terminalId: DEFAULT_TERMINAL_ID, cwd:project});
    }).pipe(Effect.scoped));
    await t3.open(thread);
    await browser.evaluate((path) => {
      const style = document.createElement("style");
      style.textContent = '[data-host-pressure] { visibility: hidden !important; } [data-host-pressure] + * { visibility: hidden !important; }';
      document.head.append(style);
      // Redact only the exact synthetic path text, before the next paint; no overlay.
      const redact = () => {
        const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
        let node;
        while ((node = walker.nextNode())) if (node.textContent?.includes(path)) node.textContent = node.textContent.replaceAll(path, "[demo checkout]");
      };
      new MutationObserver(redact).observe(document.body, {subtree:true, childList:true, characterData:true});
      redact();
    }, project);
    await screen.getByRole("button", "Git action options").tap();
    await screen.getByRole("menuitem", "Commit", {exact:true}).tap();
    await stableScreenshot(`${label}-starting-checkout`);
    await screen.getByRole("button", "Commit on new branch", {exact:true}).tap();
    await screen.getByText(/^Preparing feature branch\.\.\.$/).waitFor();
    if (detached) await git("switch", "--detach", "terminal-work");
    else await git("switch", "terminal-work");
    const success = screen.getByText(/^Committed [0-9a-f]+$/);
    const failure = screen.getByText("Action failed", {exact:true});
    await success.or(failure).first().waitFor();
    await stableScreenshot(`${label}-result`);
    const branch = (await git("branch", "--show-current")).stdout.trim();
    const branches = (await git("for-each-ref", "refs/heads/", "--format=%(refname:short)")).stdout.trim();
    const history = (await git("log", "-3", "--format=%h %s")).stdout.trim();
    const status = (await git("status", "--short")).stdout.trim();
    results.push(branch === (detached ? "" : "terminal-work") && (await git("rev-parse", "HEAD")).stdout.trim() === (await git("rev-parse", "terminal-work")).stdout.trim() && branches === "main\nterminal-work" && status.includes("README.md") && await failure.isVisible());
    // Display actual Git output beside the app result, without checkout paths or overlays.
    await screen.getByRole("button", "Toggle terminal drawer").tap();
    const terminal = screen.getByLabel("Terminal input");
    await terminal.focus();
    const completed = new Promise<void>((resolve, reject) => {
      const watcher = watch(project, () => { if (existsSync(`${project}/proof-ready`)) { watcher.close(); clearTimeout(timer); resolve(); } });
      const timer = setTimeout(() => { watcher.close(); reject(new Error("Terminal output did not complete")); }, 15000);
    });
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["terminal.write"]({threadId: ThreadId.make(thread.threadId), terminalId: DEFAULT_TERMINAL_ID,
        data: "PS1='$ '; clear; printf 'CURRENT CHECKOUT\\n'; git branch --show-current; git rev-parse --short HEAD; printf 'ALL BRANCHES\\n'; git --no-pager branch --list; printf 'HISTORY\\n'; git --no-pager log -3 --format='%h %s'; printf 'WORKING TREE\\n'; git status --short; printf '\\033[?25l'; touch proof-ready\r"});
    }).pipe(Effect.scoped));
    await completed;

    await stableScreenshot(`${label}-git-state`);
  }
  expect(results).toEqual([true,true]);
});
