import { readFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const probe = `import os, sys, tty, termios, json, select, time, pathlib
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
replies = 0
buffer = b''
replayed = False
saved_hex = ''
def line(text):
    os.write(1, (text + '\\r\\n').encode())
def save(done=False):
    with open('result.json', 'w') as f:
        json.dump({'replies': replies, 'done': done, 'replayed': replayed, 'savedHex': saved_hex}, f)
try:
    tty.setraw(fd)
    os.write(1, b'\\x1b[2J\\x1b[H\\x1b[?25l')
    line('ESC Z / DECID terminal history replay probe')
    line('One live query; reload; r replays saved bytes with PTY writer attached.')
    line('Sending: A <ESC>Z B')
    os.write(1, b'BEGIN_DECID|A\\x1bZB|END_DECID\\r\\n')
    save()
    while True:
        data = os.read(fd, 1024)
        buffer += data
        while b'\\x1b[?62;22c' in buffer:
            buffer = buffer.replace(b'\\x1b[?62;22c', b'', 1)
            replies += 1
            line('Identity reply #' + str(replies) + ': <ESC>[?62;22c')
            save()
        if b'r' in buffer and not replayed:
            buffer = buffer.replace(b'r', b'')
            logs = pathlib.Path.cwd().parents[2] / 'userdata' / 'logs' / 'terminals'
            history = next(p.read_bytes() for p in logs.glob('*.log') if b'BEGIN_DECID|' in p.read_bytes())
            payload = history.split(b'BEGIN_DECID|', 1)[1].split(b'|END_DECID', 1)[0]
            saved_hex = payload.hex(' ')
            line('Saved history payload bytes: ' + saved_hex)
            line('Replaying that saved payload into this live terminal:')
            os.write(1, payload + b'\\r\\n')
            replayed = True
            save()
        if b'v' in buffer:
            line('')
            line('FINAL: ' + str(replies) + ' identity replies for ONE query')
            line('Duplicate replies after history replay: ' + str(max(0, replies - 1)))
            line('PASS: history replay was silent' if replies == 1 else 'BUG: history replay answered the query again')
            save(True)
            while True:
                time.sleep(60)
finally:
    termios.tcsetattr(fd, termios.TCSADRAIN, old)
`;

async function result(workspace: string, done: boolean) {
  const deadline = Date.now() + 30000;
  while (Date.now() < deadline) {
    try {
      const value = JSON.parse(await readFile(`${workspace}/result.json`, "utf8"));
      if (done ? value.done : value.replies >= 1) return value;
    } catch {}
    await new Promise((resolve) => setTimeout(resolve, 100));
  }
  throw new Error("Terminal probe did not reach its milestone");
}

async function stableScreenshot(app: { screenshot(label: string): Promise<string> }, label: string) {
  let previous = await readFile(await app.screenshot(`${label}-stability`));
  for (let attempt = 0; attempt < 10; attempt++) {
    await new Promise((resolve) => setTimeout(resolve, 500));
    const current = await readFile(await app.screenshot(`${label}-stability`));
    if (previous.equals(current)) return app.screenshot(label);
    previous = current;
  }
  throw new Error("The capture did not settle");
}

test("ESC Z history replay must not send a second identity reply", WEB, async ({ t3, app, screen, browser }) => {
  const workspace = await t3.project("identity-probe", { "probe.py": probe });
  await t3.thread({ project: workspace, title: "Terminal identity replay", messages: ["Ready"] });
  await browser.emulateMedia({ reducedMotion: "reduce" });
  await t3.open();
  await screen.getByTestId("sidebar-row-card").press("Enter");
  await screen.getByRole("heading", "Terminal identity replay").textContent();
  await browser.keyboard.press("Control+j");
  await screen.getByRole("textbox", "Terminal input").textContent();
  await new Promise((resolve) => setTimeout(resolve, 2000));
  await browser.locator("canvas").last().tap();
  await browser.keyboard.type("PS1='$ '; clear; python3 probe.py");
  await browser.keyboard.press("Enter");
  await result(workspace, false);
  await stableScreenshot(app, "live-query");
  await browser.reload();
  await screen.getByRole("textbox", "Terminal input").textContent();
  await new Promise((resolve) => setTimeout(resolve, 2000));
  await browser.locator("canvas").last().tap();
  // Let the terminal attach and feed its persisted history before finalizing the probe.
  await new Promise((resolve) => setTimeout(resolve, 2000));
  await browser.keyboard.type("r");
  await new Promise((resolve) => setTimeout(resolve, 1500));
  await browser.keyboard.type("v");
  const final = await result(workspace, true);
  await new Promise((resolve) => setTimeout(resolve, 500));
  await stableScreenshot(app, "after-history-replay");
  expect(final.replies).toBe(1);
});
