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

test('BF51.4 requests localhost access only after Ollama is selected and supports local/cloud models', async ({ page }) => {
  let discoveryRequests = 0;
  let chatRequests = 0;
  await page.route('http://localhost:11434/**', async (route) => {
    const url = new URL(route.request().url());
    if (url.pathname === '/api/version') {
      discoveryRequests += 1;
      await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ version: '0.12.3-test' }) });
      return;
    }
    if (url.pathname === '/api/tags') {
      discoveryRequests += 1;
      await route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({ models: [
          { name: 'qwen3:8b', model: 'qwen3:8b', details: { family: 'qwen3', parameter_size: '8B', quantization_level: 'Q4_K_M' } },
          { name: 'gpt-oss:cloud', model: 'gpt-oss:cloud', remote_model: 'gpt-oss', remote_host: 'https://ollama.com' },
        ] }),
      });
      return;
    }
    if (url.pathname === '/api/show') {
      const body = route.request().postDataJSON() as { model?: string };
      if (body.model === 'gpt-oss:cloud') {
        await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ remote_model: 'gpt-oss', remote_host: 'https://ollama.com', capabilities: ['completion'] }) });
      } else {
        expect(body.model).toBe('qwen3:8b');
        await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ capabilities: ['completion'], details: { family: 'qwen3' } }) });
      }
      return;
    }
    if (url.pathname === '/v1/chat/completions') {
      chatRequests += 1;
      const body = route.request().postDataJSON() as { model?: string };
      expect(['qwen3:8b', 'gpt-oss:cloud']).toContain(body.model);
      await route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({ choices: [{ message: { content: body.model === 'gpt-oss:cloud' ? 'Verified Ollama Cloud response.' : 'Verified local Ollama response.' } }] }),
      });
      return;
    }
    await route.abort();
  });

  await createBrowserWorkspace(page, { workspaceName: `ollama-bf51-1-${Date.now()}` });

  await page.getByRole('button', { name: 'Open Learnitive AI' }).click();
  const ai = page.getByTestId('interactive-ai-overlay');
  await expect(ai.getByRole('button', { name: 'Use Ollama' })).toBeVisible();
  expect(discoveryRequests).toBe(0);
  await ai.getByRole('button', { name: 'Use Ollama' }).click();
  await expect.poll(() => discoveryRequests).toBeGreaterThan(0);
  await expect(ai.getByLabel('Ollama model')).toHaveValue('qwen3:8b');

  await page.getByRole('button', { name: /AI Settings/u }).click();
  const settings = page.getByTestId('topbar-ai-settings-dialog');
  await expect(settings).toBeVisible();
  await expect(settings.locator('#topbar-ai-provider')).toHaveValue('ollama');
  await expect(settings.getByTestId('topbar-ai-ollama-status')).toContainText(/Connected|Checking/u);
  await expect(settings.locator('#topbar-ai-ollama-model').locator('option[value="gpt-oss:cloud"]')).toBeEnabled();
  await settings.getByRole('button', { name: /Save AI Setup|Save AI settings/u }).click();
  await expect(settings).toBeHidden();

  await ai.getByLabel('Ask Learnitive AI…').fill('Reply with a short local test response.');
  await ai.getByRole('button', { name: 'Send message' }).click();
  await expect(ai).toContainText('Verified local Ollama response.');
  expect(chatRequests).toBeGreaterThan(0);

  await page.getByRole('button', { name: /AI Settings/u }).click();
  await expect(settings).toBeVisible();
  await settings.locator('#topbar-ai-ollama-model').selectOption('gpt-oss:cloud');
  await settings.getByRole('button', { name: /Save AI Setup|Save AI settings/u }).click();
  await expect(settings).toBeHidden();

  await ai.getByLabel('Ask Learnitive AI…').fill('Reply through Ollama Cloud.');
  await ai.getByRole('button', { name: 'Send message' }).click();
  await expect(ai).toContainText('Verified Ollama Cloud response.');
  await expect(ai).toContainText('Ollama Cloud');
});
