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

test("Opening a terminal restores a removed managed worktree", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("terminal-recovery");
  const { cli } = makeState(T3_HOME);
  const started = JSON.parse((await runPromise(cli([
    "thread", "start", project, "Prepare the workspace", "--title", "Retained branch terminal",
    "--provider", "devReplay", "--model", "multi-turn", "--worktree", "main",
    "--branch", "terminal-recovery", "--wait", "--json",
  ]))).stdout);
  const shown = JSON.parse((await runPromise(cli(["thread", "show", started.threadId, "--json"]))).stdout);
  const checkout = shown.thread.worktreePath;
  if (!checkout) throw new Error("The fixture did not create a managed worktree");
  execFileSync("git", ["worktree", "remove", "--force", checkout], { cwd: project });
  await t3.open();
  await screen.getByRole("button", "Retained branch terminal, Done, terminal-recovery", { exact: true }).press("Enter");
  await screen.getByRole("button", "Toggle terminal drawer", { exact: true }).tap();
  try {
    await expect.poll(() => existsSync(checkout)).toBe(true);
    await expect.poll(() => browser.evaluate(() => {
      const canvas = document.querySelector<HTMLCanvasElement>("[data-thread-terminal-drawer] canvas");
      const context = canvas?.getContext("2d");
      if (!canvas || !context) return false;
      const data = context.getImageData(0, 0, canvas.width, Math.min(80, canvas.height)).data;
      let ink = 0;
      for (let i = 0; i < data.length; i += 4) {
        if (Math.abs(data[i] - data[0]) + Math.abs(data[i + 1] - data[1]) + Math.abs(data[i + 2] - data[2]) > 50) ink++;
      }
      return ink > 500;
    })).toBe(true);
    await browser.locator('textarea[aria-label="Terminal input"]').focus();
    await browser.keyboard.type("PS1='$ '; clear; printf 'Working directory: '; pwd | sed 's|.*/worktrees/|managed-worktrees/|'; printf 'Branch: '; git branch --show-current; { pwd; git branch --show-current; } > .terminal-proof\n");
    await expect.poll(() => {
      try { return readFileSync(`${checkout}/.terminal-proof`, "utf8"); } catch { return ""; }
    }).toBe(`${checkout}\nterminal-recovery\n`);
  } finally {
    await screen.getByRole("button", "Toggle terminal drawer", { exact: true }).focus();
    await browser.evaluate(() => {
      const style = document.createElement("style");
      style.textContent = "*, *::before, *::after { animation: none !important; transition: none !important; caret-color: transparent !important; }";
      document.head.append(style);
    });
    await new Promise((resolve) => setTimeout(resolve, 500));
    const first = await app.screenshot("stability-check");
    await new Promise((resolve) => setTimeout(resolve, 500));
    const second = await app.screenshot("terminal-after-cleanup");
    console.log("Stable screenshots:", readFileSync(first).equals(readFileSync(second)));
  }
});
