import { execFileSync } from "node:child_process";
import { readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Completed command retains the long line before its short footer", WEB, async ({ t3, app, screen, browser }) => {
  const file = join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson");
  const original = readFileSync(file, "utf8");
  const command = `python3 -c 'import sys; sys.stdout.write("x" * 524288 + "\\nOK")'`;
  const output = execFileSync("python3", ["-c", 'import sys; sys.stdout.write("x" * 524288 + "\\nOK")'], { maxBuffer: 1048576 }).toString();
  const entries = original.trim().split("\n").map(line => JSON.parse(line));
  for (const entry of entries) {
    const update = entry.frame?.params?.update;
    if (update?.sessionUpdate === "tool_call") {
      update.title = command;
      update.rawInput = { command };
    }
    if (update?.sessionUpdate === "tool_call_update") update.rawOutput = output;
    if (update?.sessionUpdate === "agent_message_chunk") update.content.text = "Command completed: 524291 characters.";
  }
  writeFileSync(file, entries.map(entry => JSON.stringify(entry)).join("\n") + "\n");
  try {
    const project = await t3.project("output-tail-proof");
    const thread = await t3.thread({ project, title: "Long command output", messages: [command], model: "command-output" });
    await t3.open(thread);
    await screen.getByRole("button", "Worked for", { exact: false }).tap();
    await screen.getByRole("button", /^python3 -c/).tap();
    await expect(screen.getByText("Earlier output not shown")).toBeVisible();
    await app.screenshot("completed-output-tail");
    await expect.poll(() => browser.evaluate<number>(`[...document.querySelectorAll('div.max-h-80.overflow-auto')].map(e => e.textContent ?? '').filter(t => t.endsWith('OK')).reduce((n,t) => Math.max(n, (t.match(/x/g) ?? []).length), 0)`)).toBe(65533);
  } finally {
    writeFileSync(file, original);
  }
});
