/// <reference lib="dom" />
import { readFile } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { APP_DIR } from "../e2e.config.ts";
import { chromium } from "playwright-core";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Two writable viewers save Vim edits through handover and reconnect", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("PTY demo");
  const thread = await t3.thread({ project, title: "Shared terminal", messages: ["Terminal reproduction"] });
  await t3.open(thread);
  await browser.evaluate(() => { localStorage.setItem("t3code:theme", "dark"); return null; });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle thread details panel").tap();
  const url = await browser.evaluate(() => location.href);
  const peerBrowser = await chromium.launch({ headless: true });
  const context = await peerBrowser.newContext({ viewport: { width: 1280, height: 800 } });
  await context.addCookies(await browser.cookies());
  await context.addInitScript(() => localStorage.setItem("t3code:theme", "dark"));
  let peer = await context.newPage();
  const read = (file: string) => readFile(`${project}/${file}`, "utf8").catch(() => "");
  const input = screen.getByLabel("Terminal input");
  const send = async (command: string) => {
    await input.focus();
    await browser.keyboard.type(command);
    await browser.keyboard.press("Enter");
  };
  const peerSend = async (command: string) => {
    await peer.getByLabel("Terminal input").focus();
    await peer.keyboard.type(command);
    await peer.keyboard.press("Enter");
  };
  const settle = async () => { await new Promise(resolve => setTimeout(resolve, 1000)); };
  const stableCapture = async (label: string) => {
    const image = async () => {
      const path = await app.screenshot("settling");
      return readFile(path).catch(() => readFile(join(fileURLToPath(new URL("../", import.meta.url)), path)));
    };
    let previous = await image();
    for (let attempt = 0; attempt < 12; attempt++) {
      await new Promise(resolve => setTimeout(resolve, 500));
      const current = await image();
      if (previous.equals(current)) { await app.screenshot(label); return; }
      previous = current;
    }
    throw new Error("The capture did not settle to identical pixels");
  };
  const results: string[] = [];
  const idleIndicators: number[] = [];
  try {
    // Attach the separate context first so it owns query replies on the fixed app.
    await peer.goto(url);
    await peer.getByRole("button", { name: "Toggle thread details panel", exact: true }).click();
    await peer.getByRole("button", { name: "Toggle terminal drawer", exact: true }).click();
    await peer.getByLabel("Terminal input").waitFor();
    await settle();
    await peerSend("export PS1='viewer$ '; clear; echo ready > shell-ready");
    for (let attempt = 0; await read("shell-ready") !== "ready\n"; attempt++) {
      if (attempt === 8) throw new Error("Shell did not accept readiness command");
      await settle();
      await peerSend("export PS1='viewer$ '; clear; echo ready > shell-ready");
    }
    await peerSend("printf '\\033[6n'");
    await settle();
    await peer.keyboard.press("Control+u");
    await screen.getByRole("button", "Toggle terminal drawer").tap();
    await input.focus();
    await settle();
    await send("echo 'Viewer B can type'; echo B > viewer-b");
    await settle();
    if (await read("viewer-b") !== "B\n") throw new Error("Viewer B input did not reach shell");
    await peerSend("echo 'Viewer A can type'; echo A > viewer-a");
    await settle();
    if (await read("viewer-a") !== "A\n") throw new Error("Viewer A input did not reach shell");

    for (let stage = 0; stage < 3; stage++) {
      if (stage === 1) { await peer.close(); await settle(); }
      if (stage === 2) {
        peer = await context.newPage();
        await peer.goto(url);
        await peer.getByRole("button", { name: "Toggle terminal drawer", exact: true }).waitFor();
        await settle();
        if (await peer.getByLabel("Terminal input").count() === 0)
          await peer.getByRole("button", { name: "Toggle terminal drawer", exact: true }).click();
        await peer.getByLabel("Terminal input").waitFor();
        await settle();
      }
      await send("printf 'alpha\\n' > /tmp/t3-pty-query.txt; vim -Nu NONE -n -i NONE /tmp/t3-pty-query.txt");
      await settle();
      await input.focus();
      await browser.keyboard.type("iHELLO");
      await browser.keyboard.press("Escape");
      await browser.keyboard.type(":wq");
      await browser.keyboard.press("Enter");
      await settle();
      await send(`clear; printf 'Stage ${stage + 1}: ${["two writable viewers", "reply owner disconnected", "reply owner reconnected"][stage]}\\n'; cat -A /tmp/t3-pty-query.txt; cp /tmp/t3-pty-query.txt result-${stage}; ps -t $(tty) -o comm=; echo 'Shell idle'`);
      await new Promise(resolve => setTimeout(resolve, 4500));
      results.push(await read(`result-${stage}`));
      idleIndicators.push(await browser.evaluate(() => document.querySelectorAll('[aria-label="Terminal process running"]').length));
      if (stage === 2) {
        const sha = execFileSync("git", ["rev-parse", "HEAD"], { cwd: APP_DIR, encoding: "utf8" }).trim();
        await peer.screenshot({ path: join(process.env.T3_PROOF_CAPTURE_DIR!, `${sha}-reconnected-viewer.png`) });
        idleIndicators.push(await peer.getByLabel("Terminal process running", { exact: true }).count());
      }
      await stableCapture(["vim-save-two-viewers", "vim-save-after-handover", "vim-save-after-reconnect"][stage]!);
    }
    await expect({ results, idleIndicators }).toEqual({ results: ["HELLOalpha\n", "HELLOalpha\n", "HELLOalpha\n"], idleIndicators: [0, 0, 0, 0] });
  } finally { await peerBrowser.close(); }
});
