import * as fs from "node:fs/promises";
import { expect } from "e2e";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

const RUN = String.raw`while [ ! -f first ]; do sleep 0.1; done
printf '\n\0337\033[A\033[J'
touch first-written
while [ ! -f second ]; do sleep 0.1; done
printf 'A\nB\0338Z'
touch second-written
while [ ! -f finish ]; do sleep 0.1; done
`;

const REPLAY = String.raw`#!/usr/bin/env node
import { readFileSync } from "node:fs";
import { createInterface } from "node:readline";
import { spawn } from "node:child_process";
if (process.argv.includes("--version")) { console.log("codex-cli 0.157.0"); process.exit(0); }
const templates = JSON.parse(readFileSync(new URL("templates.json", import.meta.url)));
const send = (x) => process.stdout.write(JSON.stringify(x) + "\n");
let cwd;
const threadId = templates.thread.thread.id;
const turn = { id: "cursor-turn", items: [], itemsView: "notLoaded", status: "inProgress", error: null, startedAt: null, completedAt: null, durationMs: null };
const note = (method, params) => send({method, params});
for await (const line of createInterface({ input: process.stdin })) {
  const {id, method, params} = JSON.parse(line);
  if (id === undefined) continue;
  let result = {};
  if (method === "initialize") result = templates.initialize;
  if (method === "config/read") result = {config:{}, origins:{}};
  if (method === "account/read") result = {account:null, requiresOpenaiAuth:false};
  if (method === "skills/list") result = {data:[]};
  if (method === "model/list") result = {data:[], nextCursor:null};
  if (method === "thread/start") { cwd=params.cwd; result=templates.thread; result.cwd=cwd; result.thread.cwd=cwd; }
  if (method === "turn/start") result = {turn};
  send({id, result});
  if (method !== "turn/start") continue;
  note("turn/started", {threadId,turn});
  const item = {type:"commandExecution",id:"cursor-command",pluginId:null,scriptPath:null,command:"bash run.sh",cwd,processId:"1",source:"unifiedExecStartup",status:"inProgress",commandActions:[{type:"unknown",command:"bash run.sh"}],aggregatedOutput:null,exitCode:null,durationMs:null};
  note("item/started", {threadId,turnId:turn.id,item,startedAtMs:Date.now()});
  const child=spawn("bash",["run.sh"],{cwd});
  child.stdout.on("data", chunk => note("item/commandExecution/outputDelta",{threadId,turnId:turn.id,itemId:item.id,delta:chunk.toString()}));
  child.on("exit", () => { note("item/completed",{threadId,turnId:turn.id,item:{...item,status:"completed",exitCode:0}}); note("turn/completed",{threadId,turn:{...turn,status:"completed"}}); });
  process.on("exit", () => child.kill());
}
`;

test("Reopening live output keeps the saved cursor row", WEB, async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const entries = (await fs.readFile(`${APP_DIR}/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/codex_transcript.ndjson`, "utf8")).trim().split("\n").map(line => JSON.parse(line));
  const response = (label: string) => entries.find(e => e.type === "emit_inbound" && e.label === label && e.frame.result)?.frame.result;
  const templates = { initialize: response("initialize"), thread: response("thread/start") };
  const project = await t3.project("cursor-demo", { "run.sh": RUN, "replay.mjs": REPLAY, "templates.json": JSON.stringify(templates) });
  await fs.chmod(`${project}/replay.mjs`, 0o755);
  await t3.thread({ project, title: "Setup", messages: ["hello"] });
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const original = await fs.readFile(settingsPath, "utf8");
  const settings = JSON.parse(original);
  settings.providerInstances.codex = { driver: "codex", enabled: true, config: { binaryPath: `${project}/replay.mjs` } };
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  try {
    const { cli } = makeState(T3_HOME);
    const started = await runPromise(cli(["thread", "start", project, "Run bash run.sh now and wait for it to finish. Do not change the script or run any other command.", "--title", "Saved cursor live output", "--provider", "codex", "--model", "gpt-6-luna", "--json"]));
    const { threadId } = JSON.parse(started.stdout);
    await t3.open({ threadId });
    await screen.getByText("Working for", { exact: false }).first().waitFor({ timeout: 120000 });
    const command = screen.getByRole("button", "Running bash", { exact: false }).first();
    await command.tap({ timeout: 120000 });
    await screen.getByRole("button", "bash run.sh", { exact: true }).tap();
    await app.screenshot("connected-before-first-write");
    await screen.getByText("Loading output…", { exact: true }).waitFor({ state: "hidden" });
    await fs.writeFile(`${project}/first`, "");
    await expect.poll(async () => fs.readFile(`${project}/first-written`, "utf8").then(() => true).catch(() => false)).toBe(true);
    await browser.evaluate(() => {
      const frame = document.createElement("iframe");
      frame.id = "reopened";
      frame.src = location.pathname;
      frame.style.cssText = "position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647";
      document.body.append(frame);
      return null;
    });
    const reopened = browser.frameLocator("#reopened");
    await reopened.getByText("Working for", { exact: false }).first().waitFor();
    await reopened.getByRole("button", "Running bash", { exact: false }).first().tap();
    await reopened.getByRole("button", "bash run.sh", { exact: true }).tap();
    await reopened.getByText("Loading output…", { exact: true }).waitFor({ state: "hidden" });
    await app.screenshot("reopened-before-second-write");
    await fs.writeFile(`${project}/second`, "");
    await expect.poll(async () => fs.readFile(`${project}/second-written`, "utf8").then(() => true).catch(() => false)).toBe(true);
    await reopened.getByText("Z", { exact: false }).first().waitFor();
    await app.screenshot("reopened-output");
    await browser.evaluate(() => { document.querySelector<HTMLElement>("#reopened")!.style.display = "none"; return null; });
    await app.screenshot("connected-output");
    await browser.evaluate(() => { document.querySelector<HTMLElement>("#reopened")!.style.display = ""; return null; });
    await expect(reopened.getByText("A\nZ", { exact: true })).toBeVisible();
  } finally {
    await fs.writeFile(`${project}/finish`, "");
    await fs.writeFile(settingsPath, original);
  }
});
