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

test("Reopening a running command preserves build history through cursor-up redraw", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("build-demo");
  const signals = await fs.mkdtemp(path.join(T3_HOME, "progress-signals-"));
  const fixture = (await fs.readFile(path.join(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 = (method: string) => fixture.find(x => x.type === "emit_inbound" && x.frame.id !== undefined && x.label === method).frame.result;
  const command = fixture.find(x => x.label === "item/started" && x.frame.params?.item?.type === "commandExecution").frame.params.item;
  command.command = "PRE=15 PAUSE=60 TAIL=40 ./progress.sh";
  command.commandActions = [{type:"unknown", command:command.command}];
  command.cwd = project;
  const setup = response("thread/start");
  setup.cwd = project; setup.runtimeWorkspaceRoots = [project]; setup.instructionSources = [];
  setup.thread.cwd = project; setup.thread.path = null; setup.thread.environments = [{ environmentId: "local", cwd: project, runtimeWorkspaceRoots: [project] }];
  const executable = path.join(signals, "progress-codex.mjs");
  await fs.writeFile(path.join(signals,"frames.json"),JSON.stringify({setup,command,init:response("initialize")}));
  await fs.writeFile(executable, "#!" + process.execPath + "\n" + "import { createInterface } from 'node:readline';\nimport { existsSync, watch, writeFileSync, appendFileSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nconst signals = dirname(process.argv[1]);\nconst {setup,command,init} = JSON.parse(readFileSync(join(signals,'frames.json'),'utf8'));\nconst threadId = setup.thread.id, turnId = 'progress-turn';\nconst turn = {id:turnId,items:[],itemsView:'notLoaded',status:'inProgress',error:null,startedAt:1791001627,completedAt:null,durationMs:null};\nconst send = value => process.stdout.write(JSON.stringify(value)+'\\n');\nconst notify = (method, params) => send({method,params});\nconst wait = name => new Promise(resolve => { const w=watch(signals, (_e,n)=>{if(n===name){w.close();resolve();}}); if(existsSync(signals+'/'+name)){w.close();resolve();} });\nlet activeItem = command.id;\nconst delta = text => notify('item/commandExecution/outputDelta',{threadId,turnId,itemId:activeItem,delta:text});\nif(process.argv.includes('--version')) { console.log('codex-cli 0.157.0'); process.exit(0); }\nfor await (const line of createInterface({input:process.stdin})) {\n const {id,method,params} = JSON.parse(line);\n appendFileSync(signals+'/protocol.log',method+'\\n');\n if(id===undefined) continue;\n let result={};\n if(method==='initialize') result=init;\n if(method==='skills/list') result={data:[]};\n if(method==='config/read') result={config:{},origins:{}};\n if(method==='account/read') result={account:{type:'apiKey'},requiresOpenaiAuth:false};\n if(method==='account/rateLimits/read') result={rateLimits:null,rateLimitsByLimitId:null};\n if(method==='model/list') result={data:[{id:'gpt-6-luna',model:'gpt-6-luna',displayName:'Replay',description:'Replay',hidden:false,supportedReasoningEfforts:[],defaultReasoningEffort:'low',isDefault:true}],nextCursor:null};\n if(method==='thread/start'||method==='thread/resume') result=setup;\n if(method==='thread/read') result={thread:setup.thread};\n if(method==='turn/start') result={turn};\n send({id,result});\n if(method==='turn/start') {\n   notify('turn/started',{threadId,turn});\n   notify('item/started',{threadId,turnId,item:command,startedAtMs:1791001627000});\n   (async()=>{\n     await wait('history');\n     delta('Build started\\n'+'working\\n'.repeat(63)+'\\x1b[2JProgress: 10%');\n     writeFileSync(signals+'/history-sent','');\n     await wait('redraw');\n     delta('\\x1b[1A\\r\\x1b[2KProgress: 20%');\n     writeFileSync(signals+'/redraw-sent','');\n     await wait('finish');\n     delta('\\n');\n     notify('item/completed',{threadId,turnId,completedAtMs:1791001640000,item:{...command,status:'completed',exitCode:0,aggregatedOutput:'Build started\\nProgress: 20%\\n',durationMs:10000}});\n     await wait('long-start');\n     const long = {...command, id:'long-progress',command:'./long-progress.sh',commandActions:[{type:'unknown',command:'./long-progress.sh'}]};\n     activeItem = long.id;\n     notify('item/started',{threadId,turnId,item:long,startedAtMs:1791001640000});\n     await wait('long-history');\n     delta('Build started\\n'+'working\\n'.repeat(63)+'\\x1b[2J'+'x'.repeat(65536));\n     writeFileSync(signals+'/long-history-sent','');\n     await wait('long-redraw');\n     delta('\\r\\x1b[2KProgress: done');\n     writeFileSync(signals+'/long-redraw-sent','');\n     await wait('long-finish');\n     delta('\\n');\n     notify('item/completed',{threadId,turnId,completedAtMs:1791001650000,item:{...long,status:'completed',exitCode:0,aggregatedOutput:'Build started\\nProgress: done\\n',durationMs:10000}});\n     notify('turn/completed',{threadId,turn:{...turn,status:'completed'}});\n   })();\n }\n}\n", {mode:0o755});
  const settingsPath=path.join(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:executable}};
  try {
    await fs.writeFile(settingsPath,JSON.stringify(settings));
    await runPromise(Effect.gen(function*(){
      const client=yield* rpcClient(T3_HOME,app.baseUrl??"");
      yield* client.subscribeServerConfig({}).pipe(Stream.filter(e=>(e.type==="snapshot"?e.config.providers:e.type==="providerStatuses"?e.payload.providers:[]).some(p=>p.instanceId==="codex" && p.status!=="disabled")),Stream.runHead);
    }).pipe(Effect.scoped));
    const {cli}=makeState(T3_HOME);
    const started=await runPromise(cli(["thread","start",project,"Run the build progress command in the foreground","--title","Build progress","--provider","codex","--model","gpt-6-luna","--json"]));
    const {threadId}=JSON.parse(started.stdout);
    await t3.open({threadId});
    const row=screen.getByRole("button","Running progress.sh",{exact:false}).first();
    await row.waitFor({timeout:60000});
    await fs.writeFile(path.join(signals,"history"),"");
    await expect.poll(async()=>fs.access(path.join(signals,"history-sent")).then(()=>true,()=>false)).toBe(true);
    await app.screenshot("closed-after-clear");
    await row.tap();
    await screen.getByRole("button","PRE=15 PAUSE=60 TAIL=40 ./progress.sh",{exact:false}).first().tap();
    await screen.getByText("Progress: 10%",{exact:false}).waitFor({timeout:15000});
    await app.screenshot("reopened-before-redraw");
    await fs.writeFile(path.join(signals,"redraw"),"");
    await screen.getByText("Progress: 20%",{exact:false}).waitFor({timeout:15000});
    await app.screenshot("reopened-after-redraw");
    const primary = await browser.evaluate(() => document.body.innerText);
    const firstCommand=screen.getByRole("button","PRE=15 PAUSE=60 TAIL=40 ./progress.sh",{exact:false}).first();
    await firstCommand.tap();
    await fs.writeFile(path.join(signals,"finish"),"");
    await fs.writeFile(path.join(signals,"long-start"),"");
    const longCommand=screen.getByRole("button","./long-progress.sh",{exact:false}).first();
    await longCommand.waitFor({timeout:15000});
    await fs.writeFile(path.join(signals,"long-history"),"");
    await expect.poll(async()=>fs.access(path.join(signals,"long-history-sent")).then(()=>true,()=>false)).toBe(true);
    await longCommand.tap();
    await screen.getByText("xxxxxxxxxxxxxxxx",{exact:false}).waitFor({timeout:15000});
    await app.screenshot("full-length-progress");
    await fs.writeFile(path.join(signals,"long-redraw"),"");
    await screen.getByText("Progress: done",{exact:false}).waitFor({timeout:15000});
    await app.screenshot("shortened-progress");
    const shortened = await browser.evaluate(() => document.body.innerText);
    expect({
      reopenedKeepsHistory: primary.includes("Build started"),
      reopenedDropsStaleProgress: !primary.includes("Progress: 10%"),
      shortenedRestoresHistory: shortened.includes("Build started"),
    }).toEqual({
      reopenedKeepsHistory: true,
      reopenedDropsStaleProgress: true,
      shortenedRestoresHistory: true,
    });
    await fs.writeFile(path.join(signals,"long-finish"),"");

  } finally { await fs.writeFile(settingsPath,original); }
});
