/// <reference lib="dom" />
import { expect } from "e2e";
import JSZip from "jszip";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const ACP = `
import { createInterface } from 'node:readline';
import { readFileSync } from 'node:fs';
const send = x => process.stdout.write(JSON.stringify({jsonrpc:'2.0',...x})+'\\n');
for await (const line of createInterface({input:process.stdin})) {
 const {id,method,params}=JSON.parse(line);
 if(id===undefined) continue;
 if(method==='initialize') send({id,result:{protocolVersion:1,agentCapabilities:{},authMethods:[],agentInfo:{name:'Extracted text reader',version:'1'}}});
 else if(method==='session/new') send({id,result:{sessionId:'epub-reader'}});
 else if(method==='session/prompt') {
  const texts=(params.prompt??[]).filter(p=>p.type==='text').map(p=>p.text).join('\\n');
  const match=texts.match(/text extracted to: ([^)]+)/);
  let text='Ready to read an EPUB attachment.';
  if(texts.includes('Quote the first chapter')) {
   text=match ? readFileSync(match[1],'utf8') : 'I was given no extracted chapter text.';
   text='Server-provided extracted text:\\n\\n'+text+'\\n\\nExtraction read complete.';
  }
  send({method:'session/update',params:{sessionId:'epub-reader',update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text}}}});
  send({id,result:{stopReason:'end_turn'}});
 } else send({id,result:{}});
}
`;

test('An EPUB with a percent-encoded package path supplies its chapter text', WEB, async ({t3,app,browser,screen}) => {
 const epub=await new JSZip().file('mimetype','application/epub+zip',{compression:'STORE'})
 .file('META-INF/container.xml','<?xml version="1.0"?><container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"><rootfiles><rootfile full-path="OEBPS/book%201.opf" media-type="application/oebps-package+xml"/></rootfiles></container>')
 .file('OEBPS/book 1.opf','<?xml version="1.0"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0"><manifest><item id="chapter1" href="chapter1.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="chapter1"/></spine></package>')
 .file('OEBPS/chapter1.xhtml','<html xmlns="http://www.w3.org/1999/xhtml"><head><title>The Lantern Keeper</title></head><body><h1>The Lantern Keeper</h1><p>Marigold Vasquez lit the seventeenth lantern at quarter past midnight.</p></body></html>')
 .generateAsync({type:'uint8array'});
 const project=await t3.project('EPUB demonstration',{'reader.mjs':ACP});
 const instanceId=ProviderInstanceId.make('epub-text-reader');
 await runPromise(Effect.gen(function*(){
  const client=yield* rpcClient(T3_HOME,app.baseUrl??'');
  yield* client['server.updateSettings']({patch:{},providerInstanceMutation:{operation:'upsert',instanceId,instance:{driver:ProviderDriverKind.make('acpRegistry'),displayName:'Extracted text reader',enabled:true,config:{source:'local',commandPath:process.execPath,commandArgs:[project+'/reader.mjs']}}}});
 }).pipe(Effect.scoped));
 const {cli}=makeState(T3_HOME);
 const started=await runPromise(cli(['thread','start',project,'Start','--title','Percent-encoded EPUB package','--provider',instanceId,'--model','default','--wait','--json']));
 await t3.open({threadId:JSON.parse(started.stdout).threadId});
 await screen.getByText('Ready to read an EPUB attachment.').waitFor();
 const composer=browser.locator('[data-chat-composer-form="true"]');
 await composer.getByRole('textbox').fill('Quote the first chapter of the attached EPUB verbatim, using only the extracted text you were given for it. Do not open or unzip the file yourself.');
 await browser.evaluate((bytes)=>{
  const input=document.querySelector('input[type="file"]');
  if(!(input instanceof HTMLInputElement)) throw new Error('No attachment input');
  const data=new DataTransfer();
  data.items.add(new File([new Uint8Array(bytes)],'percent-path.epub',{type:'application/epub+zip'}));
  input.files=data.files;
  input.dispatchEvent(new Event('change',{bubbles:true}));
  return null;
 },Array.from(epub));
 await screen.getByRole('button','File attachment, percent-path.epub',{exact:false}).waitFor();
 await browser.keyboard.press('Enter');
 await screen.getByText('Extraction read complete.',{exact:false}).waitFor({timeout:120000});
 await app.screenshot('chapter-text');
 await expect(screen.getByText('Marigold Vasquez lit the seventeenth lantern at quarter past midnight.',{exact:false})).toBeVisible();
});
