/// <reference lib="dom" />
import { ThreadId } from '@t3tools/contracts';
import { expect } from 'e2e';
import * as Effect from 'effect/Effect';
import * as FileSystem from 'effect/FileSystem';
import { writeFile } from 'node:fs/promises';
import { execFileSync } from 'node:child_process';
import { APP_DIR, T3_HOME } from '../e2e.config.ts';
import { rpcClient, runPromise, test, WEB } from './t3.ts';
import { drainGate } from './terminal-drain-gate.ts';
const PROGRAM=String.raw`import {writeFileSync} from 'node:fs';
process.stdin.setRawMode(true);
process.stdout.write('\x1b[2J\x1b[HReal PTY ready\r\n');
writeFileSync('state','started');
process.stdin.on('data',chunk=>{
 const key=chunk.toString();
 if(key==='h') process.stdout.write('HOLD-DRAIN\r\n');
 if(key==='q') process.stdout.write('\x1b]0;Build ');
 if(key==='p') process.stdout.write('progress\x07ready-after-clear\r\n',()=>writeFileSync('state','complete'));
 if(key==='x') {process.stdout.write('progress\x07');process.exit(42);}
});`;
test('Clear retains drain ownership and delivers an already queued real PTY exit',WEB,async({t3,app,browser,screen})=>{
 const cwd=await t3.project('terminal-race-proof',{'proof.mjs':PROGRAM});
 const thread=await t3.thread({project:cwd,title:'Clear with a queued exit',messages:['hello']});
 const input={threadId:ThreadId.make(thread.threadId),terminalId:'term-1'};
 const rpc=(method:'terminal.open'|'terminal.write'|'terminal.clear',extra={})=>runPromise(Effect.gen(function*(){const client=yield* rpcClient(T3_HOME,app.baseUrl??'');return yield* client[method]({...input,...extra} as never);}).pipe(Effect.scoped));
 const readState=()=>runPromise(Effect.gen(function*(){const fs=yield* FileSystem.FileSystem;return yield* fs.readFileString(`${cwd}/state`);}).pipe(Effect.orElseSucceed(()=>'')));
 await rpc('terminal.open',{cwd,env:{PS1:'proof> ',ENV:'',T3CODE_TERMINAL_SHELL:'/bin/sh'}});
 await t3.open(thread);
 await screen.getByRole('button','Toggle terminal drawer').tap();
 const terminal=screen.getByLabel('Terminal input');
 await expect(terminal).toHaveAttribute('data-workspace-focus-default','');
 await expect.poll(async()=>{await rpc('terminal.write',{data:'stty -echo; exec node proof.mjs\r'});return readState();}).toBe('started');
 const gate=await drainGate(T3_HOME,APP_DIR);
 const trace:Record<string,unknown>={};
 try {
  await gate.arm(()=>rpc('terminal.write',{data:'h'}));
  await rpc('terminal.write',{data:'q'});
  await expect.poll(async()=> (await gate.state()).queued.some((e:any)=>e.type==='output'&&e.data.includes('Build '))).toBe(true);
  trace.ownershipBeforeClear=await gate.state();
  await rpc('terminal.clear');
  trace.ownershipAfterClear=await gate.state();
  await rpc('terminal.write',{data:'p'});
  await expect.poll(readState).toBe('complete');
  trace.newOutputWhileHeld=await gate.state();
  await app.screenshot('new-output-while-original-drain-held');
  await gate.release();
  await expect.poll(async()=> (await gate.state()).drainRunning).toBe(false);
  await app.screenshot('output-after-original-drain-resumes');

  await gate.arm(()=>rpc('terminal.write',{data:'h'}));
  await rpc('terminal.write',{data:'q'});
  await rpc('terminal.write',{data:'x'});
  await expect.poll(async()=> (await gate.state()).queued.some((e:any)=>e.type==='exit')).toBe(true);
  trace.queuedExitBeforeClear=await gate.state();
  await app.screenshot('real-pty-exit-queued-before-clear');
  await rpc('terminal.clear');
  trace.queuedExitAfterClear=await gate.state();
  await gate.release();
  await expect.poll(async()=> (await gate.state()).drainRunning).toBe(false);
  trace.queuedExitAfterRelease=await gate.state();
  await app.screenshot('queued-exit-after-clear-and-drain-release');
 }finally {await gate.release().catch(()=>{});await gate.close();}
 const sha=execFileSync('git',['rev-parse','HEAD'],{cwd:APP_DIR,encoding:'utf8'}).trim();
 await writeFile(`${process.env.PROOF_TRACE_DIR}/drain-${sha.slice(0,10)}.json`,JSON.stringify({sha,...trace},null,2));
 expect({ownership:trace.ownershipAfterClear,exit:trace.queuedExitAfterRelease}).toMatchObject({ownership:{drainRunning:true,pendingControlSequence:'\u001b]0;Build '},exit:{status:'exited',exitCode:42}});
});
