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

const notebook = JSON.stringify({nbformat:4,nbformat_minor:5,metadata:{},cells:[
 {cell_type:"markdown",metadata:{},source:["# Vessel: Larkspur"]},
 {cell_type:"code",metadata:{},source:["print(301)"],execution_count:1,outputs:[{output_type:"stream",name:"stdout",text:["301\n"]}]}
]});

async function notebooks(dir: string): Promise<string[]> {
 const entries = await readdir(dir,{withFileTypes:true}).catch(()=>[]);
 const found = await Promise.all(entries.map(e=>e.isDirectory()?notebooks(join(dir,e.name)):Promise.resolve(e.name.endsWith('.ipynb')?[join(dir,e.name)]:[])));
 return found.flat();
}

test("BOM notebook upload extracts cells and output while preserving original bytes", WEB, async ({t3,app,browser,screen})=>{
 const project=await t3.project("notebook-demo");
 const thread=await t3.thread({project,title:"Notebook extraction",messages:["Start"]});
 await t3.open(thread);
 await screen.getByText("fixture turn complete",{exact:false}).waitFor({timeout:120_000});
 await browser.evaluate((source)=>{
   const input=document.querySelector('input[type="file"][multiple]') as HTMLInputElement;
   if(!input) throw new Error('Composer file picker missing');
   const files=new DataTransfer();
   files.items.add(new File([new Uint8Array([239,187,191]),source],"bom-notebook.ipynb",{type:"application/x-ipynb+json"}));
   files.items.add(new File([source],"plain-notebook.ipynb",{type:"application/x-ipynb+json"}));
   input.files=files.files;
   input.dispatchEvent(new Event('change',{bubbles:true}));
 },notebook);
 // The plain notebook is the control and marks completion of server extraction.
 await expect.poll(async()=>{
   const files=await notebooks(join(T3_HOME,'userdata'));
   for(const file of files){
     const bytes=await readFile(file);
     if(bytes[0]!==239 && await readFile(file+'.txt','utf8').catch(()=>''))return true;
   }
   return false;
 }).toBe(true);
 const files=await notebooks(join(T3_HOME,'userdata'));
 let bomText=''; let preserved=false; let plainText='';
 for(const file of files){
   const bytes=await readFile(file);
   const text=await readFile(file+'.txt','utf8').catch(()=>'');
   if(bytes[0]===239){bomText=text;preserved=bytes.equals(Buffer.concat([Buffer.from([239,187,191]),Buffer.from(notebook)]));}
   else plainText=text;
 }
 const report=['NOTEBOOK UPLOAD: SERVER EXTRACTION','',`Plain notebook: ${plainText?'text file created':'MISSING text file'}`,`BOM notebook:   ${bomText?'text file created':'MISSING text file'}`,`Original BOM notebook bytes preserved: ${preserved?'YES':'NO'}`,'','BOM extracted text:',bomText||'(none)'].join('\n');
 await writeFile(join(project,'extraction-report.txt'),report);
 await browser.keyboard.press("Control+p");
 await screen.getByPlaceholder("Search files…").fill("extraction-report.txt");
 await screen.getByRole("option", "extraction-report.txt", {exact:false}).tap();
 await screen.getByText("NOTEBOOK UPLOAD: SERVER EXTRACTION",{exact:false}).waitFor();
 try {
  await expect.poll(()=>bomText).toContain('# Vessel: Larkspur');
  await expect(bomText).toContain('print(301)');
  await expect(bomText).toContain('301');
  await expect(preserved).toBe(true);
 } finally { await app.screenshot('notebook-extraction-result'); }
});
