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

test('R14.26.0 exposes free local AI across editor modes without silently downloading a model', async ({ page }) => {
  const workspaceName = `local-ai-r14-26-0-${Date.now()}`;
  const externalAiRequests: string[] = [];
  page.on('request', (request) => {
    if (/huggingface\.co|cdn\.jsdelivr\.net/u.test(request.url())) externalAiRequests.push(request.url());
  });

  await createBrowserWorkspace(page, { workspaceName });

  const launcher = page.getByRole('button', { name: 'Open Learnitive AI' });
  await expect(launcher).toBeVisible();
  await launcher.click();

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

  await overlay.getByRole('button', { name: 'AI settings' }).click();
  const settings = page.getByTestId('topbar-ai-settings-dialog');
  await expect(settings).toBeVisible();
  const provider = settings.locator('#topbar-ai-provider');
  await expect(provider).toHaveValue('local');
  await expect(settings).toContainText('AI settings are stored only in this browser’s IndexedDB.');
  await expect(settings).toContainText('Local AI');
  await expect(settings).toContainText('Beta');
  await expect(settings.getByTestId('automatic-ai-watcher-settings')).toBeVisible();
  await settings.getByRole('button', { name: 'Close' }).click();

  // Capability/model-state inspection may start the local worker, but opening AI
  // must never fetch the runtime or multi-GB model assets by itself.
  await page.waitForTimeout(300);
  expect(externalAiRequests).toEqual([]);

  await overlay.getByRole('tab', { name: 'Papers', exact: true }).click();
  await expect(overlay.getByTestId('interactive-paper-memory-foundation')).toContainText('does not upload papers or pretend to index them yet');

  await overlay.getByRole('button', { name: 'Close Learnitive AI' }).click();
  await expect(launcher).toBeVisible();
  await launcher.click();
  await expect(overlay.getByRole('tab', { name: 'Assistant', exact: true })).toHaveAttribute('aria-selected', 'true');
  await overlay.getByRole('button', { name: 'Close Learnitive AI' }).click();
  await expect(launcher).toBeVisible();
  await page.getByRole('button', { name: 'Visual' }).click();
  await expect(launcher).toBeVisible();
  await page.getByRole('button', { name: 'Source' }).click();
  await expect(launcher).toBeVisible();
});
