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

const saveShortcut = process.platform === 'darwin' ? 'Meta+s' : 'Control+s';

test('R14.26.2 renders trusted clickable project evidence without network retrieval', async ({ page }) => {
  const workspaceName = `rag-r14-26-2-${Date.now()}`;
  const externalAiRequests: string[] = [];
  page.on('request', (request) => {
    if (/huggingface\.co|cdn\.jsdelivr\.net|api\.openai\.com|anthropic\.com|generativelanguage/u.test(request.url())) {
      externalAiRequests.push(request.url());
    }
  });

  await createBrowserWorkspace(page, { workspaceName });
  await page.getByRole('link', { name: /^main\.tex$/ }).click();
  const source = page.getByLabel('LaTeX source editor');
  const latex = [
    '\\documentclass{article}',
    '\\begin{document}',
    '\\section{Robustness}',
    'Our method remains stable under distribution shift and repeated perturbation.',
    '\\end{document}',
    '',
  ].join('\n');
  await source.fill(latex);
  await source.press(saveShortcut);
  await expect(page.getByText('Saved', { exact: true })).toBeVisible();

  const selectedText = 'Our method remains stable under distribution shift and repeated perturbation.';
  const from = latex.indexOf(selectedText);
  await page.evaluate(({ key, filePath, text, from, to }) => {
    localStorage.setItem(key, JSON.stringify([{
      id: 'grounded-answer',
      role: 'assistant',
      content: 'The manuscript discusses robustness under distribution shift [S1].',
      createdAt: Date.now(),
      sources: [{
        sourceId: 'S1',
        file: filePath,
        line: 4,
        kind: 'prose',
        title: 'Robustness',
        excerpt: text,
        anchor: {
          filePath,
          from,
          to,
          selectedText: text,
          prefixContext: '\\section{Robustness}\n',
          suffixContext: '\n\\end{document}',
        },
      }],
    }]));
  }, {
    key: `learnitive:ai:history:v1:${workspaceName}`,
    filePath: 'main.tex',
    text: selectedText,
    from,
    to: from + selectedText.length,
  });

  await page.getByRole('button', { name: 'Open Learnitive AI' }).click();
  const overlay = page.getByTestId('interactive-ai-overlay');
  await expect(overlay).toContainText('The manuscript discusses robustness under distribution shift [S1].');
  const sourceCard = overlay.getByRole('button', { name: /\[S1\] Robustness/ });
  await expect(sourceCard).toContainText('main.tex:4');
  await sourceCard.click();
  await expect(page.getByLabel('LaTeX source editor')).toBeVisible();

  await page.waitForTimeout(200);
  expect(externalAiRequests).toEqual([]);
});
