/// <reference lib="dom" />
import { readFile, writeFile } from 'node:fs/promises';
import { expect } from 'e2e';
import { test, WEB } from './t3.ts';

const PROGRAM = String.raw`import os, sys
os.mkfifo('resume')
sys.stdout.write('\x1b[2J\x1b[Hbefore\r\n\x1bP' + 'z' * 5000)
sys.stdout.flush()
open('state','w').write('paused')
with open('resume') as fifo: fifo.read()
sys.stdout.write('\u0085ready\r\n')
sys.stdout.flush()
open('state','w').write('finished')
with open('keep-open','w') as f: pass
with open('hold','w') as f: pass
import time
time.sleep(120)
`;

test('Joining during an omitted DCS preserves subsequent NEL line movement', WEB, async ({t3, app, browser, screen}) => {
  await browser.setViewport({width:1600,height:900});
  await browser.emulateMedia({colorScheme:'dark'});
  const project = await t3.project('terminal-proof', {'probe.py':PROGRAM});
  const thread = await t3.thread({project,title:'Terminal line movement',messages:['hello']});
  const read = async (name:string) => readFile(`${project}/${name}`,'utf8').catch(()=>'');
  await t3.open(thread);
  await screen.getByRole('button','Toggle terminal drawer').tap();
  const input = screen.getByLabel('Terminal input');
  await expect.poll(async()=> {
    await input.focus();
    await browser.keyboard.type(`echo ready > '${project}/shell-ready'`);
    await browser.keyboard.press('Enter');
    return read('shell-ready');
  },{timeout:30000}).toBe('ready\n');
  await input.focus();
  await browser.keyboard.type(`cd '${project}' && python3 probe.py`);
  await browser.keyboard.press('Enter');
  await expect.poll(()=>read('state')).toBe('paused');
  await browser.evaluate(()=>{
    const frame = document.createElement('iframe');
    frame.id='joining-viewer';
    frame.src=location.href;
    frame.style.cssText='position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647';
    document.body.append(frame);
    return null;
  });
  const other = browser.frameLocator('#joining-viewer');
  await other.getByLabel('Terminal input').waitFor({timeout:30000});
  await app.screenshot('joining-viewer-before-resume');
  await writeFile(`${project}/resume`,'continue\n');
  await expect.poll(()=>read('state')).toBe('finished');
  const rows = ()=>browser.evaluate(()=>{
    function bands(doc:Document) {
      const canvas=doc.querySelector('[aria-label="Terminal input"]')!.parentElement!.querySelector('canvas')!;
      const ctx=canvas.getContext('2d')!;
      const w=Math.min(canvas.width,110), h=Math.min(canvas.height,120);
      const data=ctx.getImageData(0,0,w,h).data;
      const bg=ctx.getImageData(canvas.width-2,1,1,1).data;
      const occupied:number[]=[];
      for(let y=0;y<h;y++) {
        let n=0;
        for(let x=12;x<w;x++) {const i=(y*w+x)*4;if(Math.abs(data[i]-bg[0])+Math.abs(data[i+1]-bg[1])+Math.abs(data[i+2]-bg[2])>90)n++;}
        if(n>7) occupied.push(y);
      }
      const starts=occupied.filter((y,i)=>i===0||y>occupied[i-1]+1);
      return {starts, occupied};
    }
    return {attached:bands(document),joined:bands(document.querySelector<HTMLIFrameElement>('#joining-viewer')!.contentDocument!)};
  });
  // Wait for both renderers to paint the second word, then capture their real canvases.
  await expect.poll(async()=> (await rows()).joined.starts.length).toBe(2);
  await app.screenshot('joining-viewer-after-nel');
  await browser.evaluate(()=>{document.querySelector<HTMLIFrameElement>('#joining-viewer')!.style.visibility='hidden';return null;});
  await app.screenshot('attached-viewer-after-nel');
  const actual=await rows();
  expect(actual.joined.starts).toEqual(actual.attached.starts);
});
