/// <reference lib="dom" />
import { readdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { T3_HOME } from "../e2e.config.ts";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";
const documents = {"book.ods": "UEsDBBQAAAAIAIVwfV3ok99AYgAAADoBAAALAAAAY29udGVudC54bWyzyU9Ly0xOtUrJTy7NTc0rsbMpSUzKSbUCkwoQdl5ibqqtkoKCghKKrG5RfjmqQHJqTg5QJLWixKrAzi+/qCTDRh/KAzIwFOpjGIYsgtslwanJ+XkpJDkmOL+UQsfoowcUAFBLAQIUAxQAAAAIAIVwfV3ok99AYgAAADoBAAALAAAAAAAAAAAAAACAAQAAAABjb250ZW50LnhtbFBLBQYAAAAAAQABADkAAACLAAAAAAA=", "deck.odp": "UEsDBBQAAAAIAIVwfV1ccQCKQwAAAGAAAAALAAAAY29udGVudC54bWyzyU9Ly0xOtUrJTy7NTc0rsbNJKUostypITE9VALPyEnNTbZUUFBSU7GxKUitKrArsPPNKivJt9KE8G324DiAb3TgAUEsBAhQDFAAAAAgAhXB9XVxxAIpDAAAAYAAAAAsAAAAAAAAAAAAAAIABAAAAAGNvbnRlbnQueG1sUEsFBgAAAAABAAEAOQAAAGwAAAAAAA=="};
test("Blank OpenDocument names use readable fallbacks", WEB, async ({t3,app,browser,screen}) => {
 const project=await t3.project("documents");
 const thread=await t3.thread({project,title:"OpenDocument review",messages:["Start"],model:"showcase"});
 await t3.open(thread);
 const input='[data-chat-composer-form] input[type="file"]';
 await browser.locator(input).waitFor({state:"attached"});
 await browser.evaluate(({input,documents})=>{
 const picker=document.querySelector<HTMLInputElement>(input)!;
 const files=new DataTransfer();
 for(const [name,data] of Object.entries(documents)) files.items.add(new File([Uint8Array.from(atob(data),c=>c.charCodeAt(0))],name,{type:name.endsWith("ods")?"application/vnd.oasis.opendocument.spreadsheet":"application/vnd.oasis.opendocument.presentation"}));
 picker.files=files.files;picker.dispatchEvent(new Event("change",{bubbles:true}));return null;
 },{input,documents});
 const picker=screen.getByRole("combobox","Sheet",{exact:true});
 for(let attempt=0;attempt<4;attempt++) {
  await screen.getByRole("button",/^File attachment, book\.ods/).tap();
  try { await picker.waitFor({timeout:10000}); break; } catch(error) {
   if(attempt===3) throw error;
   await browser.keyboard.press("Escape");
  }
 }
 await browser.locator('[role="table"]').waitFor();
 const first=await browser.evaluate(()=>document.querySelector('[role="combobox"][aria-label="Sheet"]')?.textContent);
 const table=await browser.evaluate(()=>document.querySelector('[role="table"]')?.getAttribute('aria-label'));
 await picker.tap();
 await screen.getByRole("option","Second",{exact:true}).waitFor();
 await app.screenshot("sheet-name-picker");
 await screen.getByRole("option","Second",{exact:true}).tap();
 await screen.getByText("South",{exact:true}).waitFor();
 await app.screenshot("named-second-sheet");
 const second=await browser.evaluate(()=>document.querySelector('[role="combobox"][aria-label="Sheet"]')?.textContent);
 await browser.keyboard.press("Escape");
 await screen.getByRole("button",/^File attachment, deck\.odp/).tap();
 try { await browser.locator('iframe[title^="deck.odp:"]').waitFor({timeout:10000}); } catch {
  await screen.getByRole("button",/^File attachment, deck\.odp/).tap();
  await browser.locator('iframe[title^="deck.odp:"]').waitFor();
 }
 const title=await browser.evaluate(()=>document.querySelector('iframe[title^="deck.odp:"]')?.getAttribute('title'));
 await app.screenshot("blank-slide-name");
 await browser.keyboard.press("Escape");
 await screen.getByRole("textbox").tap();
 await browser.keyboard.press("End");
 await browser.keyboard.type(" summarize these");
 await app.screenshot("documents-ready-to-send");
 await screen.getByRole("button","Submit message",{exact:true}).tap();
 await browser.locator('[data-message-role="user"]').filter({hasText:"summarize these"}).waitFor();
 await app.screenshot("sent-document-attachments");
 const sidecars=await readdir(join(T3_HOME,"userdata","attachments"),{recursive:true});
 const ods=sidecars.find(path=>path.endsWith(".ods.txt"))!;
 const extracted=await readFile(join(T3_HOME,"userdata","attachments",ods),"utf8");
 await writeFile(join(project,"extracted-sheet.txt"),extracted);
 await browser.keyboard.press("Control+p");
 await screen.getByPlaceholder("Search files…").fill("extracted-sheet.txt");
 await screen.getByRole("option","extracted-sheet.txt",{exact:false}).tap();
 await screen.getByText("North",{exact:false}).waitFor();
 await app.screenshot("extracted-sheet-heading");
 await expect({first,second,table,title,extracted}).toEqual({first:"Sheet 1",second:"Second",table:"book.ods: Sheet 1",title:"deck.odp: Page 1",extracted:"## Sheet: Untitled\nNorth\n\n## Sheet: Second\nSouth"});
});
