import { expect, test } from '@playwright/test';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { loadBrowserWorkspaceFixture } from './common';

const fixtureDirectory = path.join(
  path.dirname(fileURLToPath(import.meta.url)),
  'fixtures/workspaces/live-draft-r4',
);

test('R5 Live PDF enables only after the real BusyTeX Lua gate and remains isolated from manual Compile', async ({ page, browserName }) => {
  test.skip(browserName !== 'chromium', 'The production Live PDF gate is certified against the browser BusyTeX runtime in Chromium.');
  test.setTimeout(300_000);

  const workspaceName = `live-pdf-r5-${Date.now()}`;
  await loadBrowserWorkspaceFixture(page, fixtureDirectory, { workspaceName });
  const manualStatus = await page.getByTestId('interactive-log-status-dot').getAttribute('data-compile-status');

  const toggle = page.getByTestId('live-pdf-toggle');
  await toggle.click();
  await expect(toggle).toHaveAttribute('aria-pressed', 'true', { timeout: 240_000 });
  await expect(page.getByTestId('interactive-pdf-preview')).toContainText('Live PDF · BusyTeX LuaLaTeX');
  await expect(page.getByTestId('synctex-scroll-link')).toBeEnabled({ timeout: 240_000 });
  await expect(page.getByTestId('synctex-status')).toContainText('SyncTeX ready');
  expect(await page.getByTestId('interactive-log-status-dot').getAttribute('data-compile-status')).toBe(manualStatus);

  const preview = page.getByTestId('interactive-pdf-preview');
  const beforeGeneration = await preview.getAttribute('data-pdf-generation');
  const source = page.getByLabel('LaTeX source editor');
  await source.fill('\\documentclass{article}\n\\begin{document}\nLive PDF refresh marker.\n\\newpage\nSecond page.\n\\end{document}\n');
  await expect(preview).not.toContainText('reconciling');
  await expect.poll(
    () => preview.getAttribute('data-pdf-generation'),
    { timeout: 240_000 },
  ).not.toBe(beforeGeneration);
  await expect(preview).toContainText('Live PDF', { timeout: 240_000 });
  await expect(page.getByTestId('synctex-scroll-link')).toBeEnabled({ timeout: 240_000 });
  await expect(toggle).toHaveAttribute('aria-pressed', 'true');

  await toggle.click();
  await expect(toggle).toHaveAttribute('aria-pressed', 'false');
});


test('R6 Live PDF paints an eligible prose edit before exact R5 reconciliation and keeps manual Compile isolated', async ({ page, browserName }) => {
  test.skip(browserName !== 'chromium', 'R6 uses the certified Chromium BusyTeX LuaLaTeX runtime.');
  test.setTimeout(300_000);

  const workspaceName = `live-pdf-r6-${Date.now()}`;
  await loadBrowserWorkspaceFixture(page, fixtureDirectory, { workspaceName });
  const manualStatus = await page.getByTestId('interactive-log-status-dot').getAttribute('data-compile-status');
  const toggle = page.getByTestId('live-pdf-toggle');
  await toggle.click();
  await expect(toggle).toHaveAttribute('aria-pressed', 'true', { timeout: 240_000 });
  await expect(page.getByTestId('synctex-status')).toContainText('SyncTeX ready', { timeout: 240_000 });

  // The warm R6 lane starts after the exact R5 baseline. Give its isolated
  // LuaLaTeX worker a bounded opportunity to initialize before measuring the
  // keystroke-to-overlay path.
  await page.waitForTimeout(1_500);
  const source = page.getByLabel('LaTeX source editor');
  await source.press('ControlOrMeta+Home');
  for (let line = 0; line < 7; line += 1) await source.press('ArrowDown');
  await source.press('End');
  await page.keyboard.type(' Instant R6 marker.');

  const instantPatch = page.getByTestId('live-pdf-instant-patch');
  await expect(instantPatch).toHaveAttribute('data-instant-ready', 'true', { timeout: 5_000 });
  await expect(page.getByTestId('interactive-pdf-preview')).toContainText('Live PDF · instant');
  expect(await page.getByTestId('interactive-log-status-dot').getAttribute('data-compile-status')).toBe(manualStatus);

  // R5 remains the exact authority and must replace the transient overlay once
  // its same-source PDF/SyncTeX generation is accepted.
  await expect(instantPatch).toHaveCount(0, { timeout: 240_000 });
  await expect(page.getByTestId('synctex-scroll-link')).toBeEnabled();
  expect(await page.getByTestId('interactive-log-status-dot').getAttribute('data-compile-status')).toBe(manualStatus);

  await toggle.click();
  await expect(toggle).toHaveAttribute('aria-pressed', 'false');
});
