/// <reference lib="dom" />
// @effect-diagnostics nodeBuiltinImport:off -- Stages a deterministic ACP file-reading agent.
import * as fs from "node:fs/promises";
import * as path from "node:path";
import JSZip from "jszip";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB, makeState, runPromise } from "./t3.ts";

const R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
async function workbook(custom: boolean) {
  const z = new JSZip();
  const root = custom ? "docs" : "xl";
  const book = custom ? "book.xml" : "workbook.xml";
  z.file("[Content_Types].xml", `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/${root}/${book}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/></Types>`);
  z.file("_rels/.rels", `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="office" Type="${R}/officeDocument" Target="${root}/${book}"/></Relationships>`);
  z.file(`${root}/${book}`, `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="${R}"><sheets><sheet name="Data" sheetId="1" r:id="sheet1"/></sheets></workbook>`);
  z.file(`${root}/_rels/${book}.rels`, `<Relationships><Relationship Id="sheet1" Type="${R}/worksheet" Target="sheets/sheet1.xml"/><Relationship Id="strings" Type="${R}/sharedStrings" Target="sharedStrings.xml"/><Relationship Id="styles" Type="${R}/styles" Target="styles.xml"/></Relationships>`);
  z.file(`${root}/sharedStrings.xml`, '<sst><si><t>hello</t></si><si><t>quarterly-growth</t></si></sst>');
  z.file(`${root}/styles.xml`, '<styleSheet><numFmts count="1"><numFmt numFmtId="164" formatCode="0.0%"/></numFmts><cellXfs count="2"><xf numFmtId="0"/><xf numFmtId="164"/></cellXfs></styleSheet>');
  z.file(`${root}/sheets/sheet1.xml`, '<worksheet><sheetData><row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1" s="1"><v>0.25</v></c></row><row r="2"><c r="A2" t="s"><v>1</v></c><c r="B2" s="1"><v>0.125</v></c></row></sheetData></worksheet>');
  return z.generateAsync({ type: "uint8array" });
}
const ACP = `import {createInterface} from 'node:readline';
import {readFileSync} from 'node:fs';
const sessionId='xlsx-proof';
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,agentInfo:{name:'Extracted text reader',version:'1'},agentCapabilities:{},authMethods:[]}});
 else if(method==='session/new')send({id,result:{sessionId}});
 else if(method==='session/prompt') {
 const prompt=(params.prompt??[]).map(p=>p.text??'').join('\\n');
 const paths=[...prompt.matchAll(/Attached file "([^"]+)"[^\\n]*?text extracted to: ([^)]+)/g)];
 let text='Ready to read spreadsheet extracted text.';
 if(paths.length)text=paths.map(m=>'### '+(m[1].includes('custom-workbook')?'Custom workbook root':'Standard workbook control')+'\\n\\n'+readFileSync(m[2],'utf8')).join('\\n\\n');
 send({method:'session/update',params:{sessionId,update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text}}}});
 send({id,result:{stopReason:'end_turn'}});
 }else send({id,result:{}});
}`;

test("Custom workbook root reaches the agent as extracted spreadsheet text", WEB, async ({t3,app,browser,screen})=>{
 const custom = await workbook(true); const control = await workbook(false);
 const project=await t3.project("spreadsheet-proof");
 const script=path.join(project,'reader.mjs'); await fs.writeFile(script,ACP);
 const settingsPath=path.join(T3_HOME,'userdata/settings.json');
 const settings=JSON.parse(await fs.readFile(settingsPath,'utf8'));
 settings.providerInstances['xlsx-reader']={driver:'acpRegistry',displayName:'Extracted text reader',enabled:true,config:{source:'local',commandPath:process.execPath,commandArgs:[script]}};
 await fs.writeFile(settingsPath,JSON.stringify(settings));
 const {cli}=makeState(T3_HOME);
 let threadId;
 for(let i=0;i<8&&!threadId;i++) {
 const r=await runPromise(cli(['thread','start',project,'Ready','--title','XLSX extracted text proof','--provider','xlsx-reader','--model','default','--wait','--json'],[0,1]));
 if(r.stdout.includes('threadId'))threadId=JSON.parse(r.stdout).threadId;
 }
 if(!threadId)throw Error('Reader provider did not start');
 await t3.open({threadId});
 const composer=screen.getByRole('textbox');
 await composer.fill('Read both spreadsheets using only their extracted text files. Quote the extracted text verbatim.');
 await browser.evaluate(({custom,control})=>{
 const input=document.querySelector<HTMLInputElement>('input[type="file"]')!;
 const dt=new DataTransfer();
 for(const [name,bytes] of [['custom-workbook-root.xlsx',custom],['standard-xl-control.xlsx',control]] as const)dt.items.add(new File([new Uint8Array(bytes)],name,{type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));
 input.files=dt.files;input.dispatchEvent(new Event('change',{bubbles:true}));
 return null;
 },{custom:Array.from(custom),control:Array.from(control)});
 await screen.getByText('custom-workbook-root.xlsx',{exact:true}).waitFor();
 await composer.press('Enter');
 await screen.getByText('Standard workbook control',{exact:false}).waitFor({timeout:60000});
 await app.screenshot('extracted-spreadsheet-text');
 const text=await browser.evaluate(()=>document.body.innerText);
 expect(text.split('Custom workbook root')[1]?.split('Standard workbook control')[0]).toContain('quarterly-growth');
 expect(text.split('Custom workbook root')[1]?.split('Standard workbook control')[0]).toContain('format=0.0%');
});
