/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { runPromise, test, WEB } from "./t3.ts";

const PROBE = String.raw`import {writeFileSync} from 'node:fs';
const log=new URL('received',import.meta.url);
writeFileSync(log,'');
let received=Buffer.alloc(0);
process.stdin.setRawMode(true);
process.stdin.on('data',chunk=>{
 const hex=Array.from(chunk,b=>b.toString(16).padStart(2,'0')).join(' ');
 received=Buffer.concat([received,chunk]);
 writeFileSync(log,Array.from(received,b=>b.toString(16).padStart(2,'0')).join(' '));
 process.stdout.write('\r\nRECV '+hex+'\r\n');
});
process.stdout.write('\x1b[2J\x1b[H\x1b]0;'+'T'.repeat(4000)+'\x1b[?2004h'+('A'.repeat(1000)+'\n').repeat(521)+'\r\nREADY\r\n\x1b[5n');
`;

test('Reattached clipped terminal history keeps bracketed paste', WEB, async ({t3,app,browser,screen})=>{
 const project=await t3.project('terminal-demo',{'probe.mjs':PROBE});
 const thread=await t3.thread({project,title:'Terminal snapshot paste',messages:['hello']});
 const read=(file:string)=>runPromise(Effect.gen(function*(){const fs=yield* FileSystem.FileSystem;return yield* fs.readFileString(`${project}/${file}`)}).pipe(Effect.orElseSucceed(()=>'')));
 await t3.open(thread);
 await screen.getByRole('button','Toggle terminal drawer').tap();
 const terminal=screen.getByLabel('Terminal input');
 await expect.poll(async()=>{await terminal.focus();await browser.keyboard.press('Control+c');await browser.keyboard.type('echo ready > shell-ready');await browser.keyboard.press('Enter');return read('shell-ready')},{timeout:30000}).toBe('ready\n');
 await terminal.focus();
 await browser.keyboard.type('node probe.mjs');
 await browser.keyboard.press('Enter');
 await expect.poll(()=>read('received'),{timeout:15000}).toContain('1b 5b 30 6e');
 const paste=async(text:string)=>{
  await terminal.focus();
  await browser.evaluate((text)=>{const data=new DataTransfer();data.setData('text/plain',text);document.activeElement!.dispatchEvent(new ClipboardEvent('paste',{clipboardData:data,bubbles:true,cancelable:true}));return null},text);
 };
 await paste('LIVE');
 await expect.poll(()=>read('received')).toContain('4c 49 56 45');
 await app.screenshot('live-paste');
 await browser.evaluate(()=>{location.reload();return null});
 await terminal.focus();
 await browser.keyboard.press('Enter');
 await expect.poll(()=>read('received'),{timeout:15000}).toContain('0d');
 await paste('AFTER');
 await expect.poll(()=>read('received')).toContain('41 46 54 45 52');
 await expect.poll(()=>browser.evaluate(()=>document.body.textContent?.includes('Syncing messages') ?? false),{timeout:30000}).toBe(false);
 await app.screenshot('paste-after-reattach');
 expect(await read('received')).toContain('1b 5b 32 30 30 7e 41 46 54 45 52 1b 5b 32 30 31 7e');
});
