import { expect, test } from '@playwright/test';
import { createBrowserWorkspace } from './common';

function pdfText(text: string): string {
  return text.replaceAll('\\', '\\\\').replaceAll('(', '\\(').replaceAll(')', '\\)');
}

function makePdf(text: string): Buffer {
  const stream = `BT /F1 12 Tf 50 740 Td (${pdfText(text)}) 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 612 792] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>',
    `<< /Length ${Buffer.byteLength(stream)} >>\nstream\n${stream}\nendstream`,
    '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',
  ];
  let source = '%PDF-1.4\n';
  const offsets: number[] = [0];
  objects.forEach((object, index) => {
    offsets.push(Buffer.byteLength(source));
    source += `${index + 1} 0 obj\n${object}\nendobj\n`;
  });
  const xref = Buffer.byteLength(source);
  source += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
  for (let index = 1; index <= objects.length; index += 1) source += `${String(offsets[index]).padStart(10, '0')} 00000 n \n`;
  source += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
  return Buffer.from(source, 'ascii');
}

const selectAll = process.platform === 'darwin' ? 'Meta+a' : 'Control+a';

test('R29 PM7 exposes the simplified AI, Evidence and Comment manuscript workflow from Source and Visual selections', async ({ page }) => {
  const workspaceName = `papers-pm7-${Date.now()}`;
  const modelRequests: string[] = [];
  page.on('request', (request) => {
    if (/huggingface\.co|cdn\.jsdelivr\.net|litert|gemma-4/iu.test(request.url())) modelRequests.push(request.url());
  });

  await createBrowserWorkspace(page, { workspaceName });
  const source = page.getByLabel('LaTeX source editor');
  await source.fill(String.raw`\documentclass{article}
\begin{document}
Robust local research uses AdamW for optimization.
\end{document}`);

  await page.getByRole('button', { name: 'Open Learnitive AI' }).click();
  await page.getByTestId('interactive-ai-overlay').getByRole('tab', { name: 'Papers' }).click();
  const panel = page.getByTestId('interactive-paper-memory');
  await page.getByLabel('Add research PDFs to Papers').setInputFiles({
    name: 'supporting-paper.pdf',
    mimeType: 'application/pdf',
    buffer: makePdf('Results Robust local research uses AdamW for optimization and improves reproducibility.'),
  });
  await expect(panel.getByRole('button', { name: /1 paper$/ })).toBeVisible({ timeout: 20_000 });
  await page.getByRole('button', { name: 'Close Learnitive AI' }).click();

  await source.press(selectAll);
  const actions = page.getByTestId('paper-memory-manuscript-actions');
  await expect(actions).toBeVisible();
  await expect(actions.getByRole('button', { name: 'AI' })).toBeVisible();
  await expect(actions.getByRole('button', { name: 'Evidence' })).toBeVisible();
  await expect(actions.getByRole('button', { name: 'Comment' })).toBeVisible();
  await expect(actions.getByRole('button', { name: 'Find citation' })).toHaveCount(0);
  await actions.getByRole('button', { name: 'AI' }).click();

  const overlay = page.getByTestId('interactive-ai-overlay');
  await expect(overlay).toBeVisible();
  await expect(overlay.getByRole('tab', { name: 'Assistant' })).toHaveAttribute('aria-selected', 'true');
  expect(modelRequests).toEqual([]);

  await page.getByRole('button', { name: 'Close Learnitive AI' }).click();
  await page.getByRole('button', { name: 'Visual' }).click();
  const paragraph = page.locator('.interactive-latex-visual-editor .interactive-visual-paragraph').filter({ hasText: 'Robust local research' }).first();
  await expect(paragraph).toBeVisible();
  await paragraph.click();
  await page.keyboard.press('Home');
  await page.keyboard.press('Shift+End');
  await expect(actions).toBeVisible();
  await expect(actions.getByRole('button', { name: 'AI' })).toBeVisible();
  await expect(actions.getByRole('button', { name: 'Evidence' })).toBeVisible();
  await expect(actions.getByRole('button', { name: 'Comment' })).toBeVisible();
  await actions.getByRole('button', { name: 'AI' }).click();
  await expect(overlay.getByRole('tab', { name: 'Assistant' })).toHaveAttribute('aria-selected', 'true');
  expect(modelRequests).toEqual([]);
});
