/// <reference lib="dom" />
import { expect } from "e2e";
import JSZip from "jszip";
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";

async function workbook(shared: boolean) {
  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"/></Types>');
  zip.file('xl/workbook.xml', '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Ledger" sheetId="1" r:id="rId1"/></sheets></workbook>');
  zip.file('xl/_rels/workbook.xml.rels', '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>');
  zip.file('xl/sharedStrings.xml', '<sst><si><t>_x000D_</t></si><si><t>Balance due</t></si></sst>');
  const rows = Array.from({length:10001}, (_, i) => `<row r="${i+1}"><c r="A${i+1}" t="${shared?'s':'inlineStr'}">${shared?'<v>0</v>':'<is><t>_x000D_</t></is>'}</c></row>`).join('');
  zip.file('xl/worksheets/sheet1.xml', `<worksheet><sheetData>${rows}<row r="10002"><c r="A10002" t="s"><v>1</v></c><c r="B10002"><v>240</v></c></row></sheetData></worksheet>`);
  return zip.generateAsync({type:'base64'});
}

test('XLSX whitespace-only escaped rows leave the balance in extracted attachment text', WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project('ledger-proof');
  const thread = await t3.thread({project, title:'Ledger attachment extraction', messages:['Start']});
  await t3.open(thread);
  await screen.getByText('first fixture turn complete', {exact:false}).waitFor();
  const outputs: string[] = [];
  const seen = new Set<string>();
  for (const shared of [true, false]) {
    const name = `ledger-${shared?'shared':'inline'}.xlsx`;
    const base64 = await workbook(shared);
    await screen.getByRole('textbox').fill('Read only the extracted text file of the attached workbook (do not open the xlsx itself). What is the Balance due? Quote the last 3 lines of the extracted text verbatim.');
    await browser.evaluate(({name, base64}) => {
      const clipboardData = new DataTransfer();
      clipboardData.items.add(new File([Uint8Array.from(atob(base64), c => c.charCodeAt(0))],name,{type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));
      document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent('paste',{clipboardData,bubbles:true,cancelable:true}));
    }, {name, base64});
    await screen.getByRole('button', 'Submit message', {exact:true}).tap();
    const dir = join(T3_HOME,'userdata','attachments');
    let texts: string[] = [];
    await expect.poll(async () => {
      const files = await readdir(dir, {recursive:true});
      texts = files.filter(f => f.endsWith('.xlsx.txt') && !f.startsWith('pending-'));
      return texts.length;
    }).toBe(shared?1:2);
    const added = texts.find(f => !seen.has(f))!;
    seen.add(added);
    outputs.push(`${name}\n${await readFile(join(dir,added),'utf8')}`);
    if (shared) await screen.getByText('second fixture turn complete', {exact:false}).waitFor();
    await screen.getByRole('button', 'Submit message', {exact:true}).waitFor();
  }
  // Show the server-created sidecar contents in the real app's file viewer.
  await writeFile(join(project,'extracted-ledgers.txt'), outputs.join('\n\n'));
  await browser.keyboard.press('Control+p');
  await screen.getByPlaceholder('Search files…').fill('extracted-ledgers.txt');
  await screen.getByRole('option','extracted-ledgers.txt',{exact:false}).tap();
  await browser.locator('[data-active-tab="true"]').getByText('extracted-ledgers.txt',{exact:true}).waitFor();
  await expect.poll(() => browser.evaluate(() => {
    const panel = document.querySelector('[data-right-panel-surface-content]');
    for (const host of panel?.querySelectorAll('*') ?? []) {
      const content = host.shadowRoot?.querySelector('[data-content]');
      if (content) return content.textContent ?? '';
    }
    return panel?.textContent ?? '';
  })).toContain('ledger-inline.xlsx');
  try {
    expect(outputs.every(text => /Balance due\s+240/.test(text))).toBe(true);
  } finally {
    await app.screenshot('extracted-ledgers');
  }
});
