/// <reference lib="dom" />
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 } from "./t3.ts";

async function workbook(flag: string) {
  const zip = new JSZip();
  zip.file("[Content_Types].xml", '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml"/><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/></Types>');
  zip.file("_rels/.rels", '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>');
  zip.file("xl/workbook.xml", `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><workbookPr date1904="${flag}"/><sheets><sheet name="Dates" sheetId="1" r:id="rId1"/></sheets></workbook>`);
  zip.file("xl/_rels/workbook.xml.rels", '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>');
  zip.file("xl/styles.xml", '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><cellXfs count="1"><xf numFmtId="14"/></cellXfs></styleSheet>');
  zip.file("xl/worksheets/sheet1.xml", '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData><row r="1"><c r="A1" s="0"><v>1</v></c></row></sheetData></worksheet>');
  return zip.generateAsync({type:"uint8array"});
}

test("Padded Excel date1904 true uses the 1904 system in uploaded extraction", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Workbook-proof", {
    "padded-1904.xlsx": await workbook(" true "),
    "exact-1904.xlsx": await workbook("true"),
  });
  const thread = await t3.thread({project, title:"Excel date system", messages:["Start"]});
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", {exact:false}).waitFor();
  const names = ["padded-1904.xlsx", "exact-1904.xlsx"];
  await screen.getByRole("textbox").fill("Read the attached workbooks and tell me the date in A1 of each.");
  await browser.locator('form[data-chat-composer-form] input[type="file"]').setInputFiles(names.map(name => path.join(project,name)));
  for (const name of names) await screen.getByRole("button", `File attachment, ${name},`, {exact:false}).waitFor();
  await screen.getByRole("button", "Submit message", {exact:true}).tap();
  await screen.getByRole("button", "Fork from this response").nth(1).waitFor();
  const files = await fs.readdir(path.join(T3_HOME,"userdata/attachments"));
  const sidecars = files.filter(f => !f.startsWith("pending-") && f.endsWith(".xlsx.txt"));
  const outputs: string[] = [];
  for (const name of names) {
    const padded = name.startsWith("padded");
    let sidecar: string | undefined;
    for (const file of sidecars) {
      const archive = await JSZip.loadAsync(await fs.readFile(path.join(T3_HOME,"userdata/attachments",file.slice(0,-4))));
      const xml = await archive.file("xl/workbook.xml")!.async("string");
      if (xml.includes('date1904=" true "') === padded) sidecar = file;
    }
    if (!sidecar) throw new Error("Thread-owned workbook sidecar missing");
    outputs.push(`${name} — workbookPr date1904=${padded ? '\" true \"' : '\"true\"'}\n${await fs.readFile(path.join(T3_HOME,"userdata/attachments",sidecar),"utf8")}`);
  }
  // Display the real server sidecars verbatim in the app's file viewer; replay does not interpret files.
  await fs.writeFile(path.join(project,"server-extraction.txt"), "SERVER EXTRACTION AFTER UPLOAD AND SEND\nA1 = serial 1, date style numFmtId 14\n\n" + outputs.join("\n\n"));
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("server-extraction.txt");
  await screen.getByRole("option", "server-extraction.txt", {exact:false}).tap();
  await screen.getByText("SERVER EXTRACTION AFTER UPLOAD AND SEND", {exact:false}).waitFor();
  await app.screenshot("workbook-date-system");
  expect(outputs[0]).toContain("date system 1904");
});
