/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { runPromise, test, WEB } from "./t3.ts";

function pdf(version: number) {
  const stream = `${version === 2 ? '1 0.8 0.85' : '1 1 1'} rg 0 0 600 700 re f\n${version === 2 ? '0.8 0 0' : '0 0 0'} rg BT /F1 52 Tf 65 520 Td (Version ${version}) Tj ET`;
  const objects = [
    '<< /Type /Catalog /Pages 2 0 R >>',
    '<< /Type /Pages /Kids [3 0 R] /Count 1 >>',
    '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 700] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>',
    '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',
    `<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`,
  ];
  let out = '%PDF-1.4\n';
  const offsets = [0];
  objects.forEach((object, i) => { offsets.push(out.length); out += `${i + 1} 0 obj\n${object}\nendobj\n`; });
  const xref = out.length;
  out += `xref\n0 6\n0000000000 65535 f \n${offsets.slice(1).map(n => `${String(n).padStart(10, '0')} 00000 n \n`).join('')}trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
  return new TextEncoder().encode(out);
}

test('Refresh workspace files reloads the open PDF after an external overwrite', WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project('pdf-demo', { 'report.pdf': pdf(1) });
  const thread = await t3.thread({ project, title: 'Review report', messages: ['Start'] });
  await t3.open(thread);
  await screen.getByRole('button', 'Toggle right panel').tap();
  await screen.getByText('Files', { exact: true }).tap();
  const openPdf = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll('*')) {
      const row = host.shadowRoot?.querySelector<HTMLElement>('[data-item-path="report.pdf"]');
      if (row) { row.click(); return true; }
    }
    return false;
  });
  await expect.poll(openPdf).toBe(true);
  const text = () => browser.evaluate(() => document.querySelector('[data-pdf-text-layer]')?.textContent ?? '');
  await expect.poll(text, { timeout: 120_000 }).toContain('Version 1');
  await app.screenshot('original-pdf');
  await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.writeFile(`${project}/report.pdf`, pdf(2))));
  await screen.getByRole('button', 'Refresh workspace files').tap();
  try {
    await expect.poll(text).toContain('Version 2');
  } finally {
    await app.screenshot('after-refresh');
  }
});
