import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { expect, test } from '@playwright/test';
import { createBrowserWorkspace } from './common';
import { activateProFromAiLauncher, installProActivationRoute } from './pro-license-fixture';

const fixture = path.resolve(
  path.dirname(fileURLToPath(import.meta.url)),
  '../fixtures/interactive-source-project.zip',
);

test('R10 uses a BYOK provider directly and reviews AI source changes before applying them', async ({ page }) => {
  await installProActivationRoute(page);
  let requestCount = 0;
  await page.route('https://api.openai.com/v1/chat/completions', async (route) => {
    requestCount += 1;
    const body = route.request().postDataJSON() as { model?: string };
    expect(body.model).toBe('test-model');
    const content = requestCount === 1
      ? JSON.stringify({
          message: 'I will inspect the current source before proposing a change.',
          toolCalls: [{ id: 'read-1', name: 'read_file', arguments: { file: 'main.tex' } }],
        })
      : JSON.stringify({
          message: 'I found the requested sentence and prepared a minimal source change.',
          toolCalls: [{
            id: 'patch-1',
            name: 'apply_patch',
            arguments: {
              file: 'main.tex',
              replacements: [{ find: 'Hello Learnitive.', replace: 'Hello from Learnitive AI.' }],
            },
          }],
        });
    await route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify({ choices: [{ message: { content } }] }),
    });
  });

  const workspaceName = `latex-r10-${Date.now()}`;
  await createBrowserWorkspace(page, { workspaceName });
  await page.getByLabel('Import Project ZIP').setInputFiles(fixture);
  await page.getByRole('link', { name: /^main\.tex$/ }).click();

  await activateProFromAiLauncher(page);
  await page.getByRole('button', { name: 'Open Learnitive AI' }).click();
  const ai = page.getByTestId('interactive-ai-overlay');
  await expect(ai).toBeVisible();
  await ai.getByRole('button', { name: 'AI settings' }).click();
  await ai.locator('#interactive-ai-provider').selectOption('openai');
  await ai.getByText('Privacy Mode', { exact: true }).locator('..').locator('..').getByRole('checkbox').uncheck();
  await ai.getByLabel('Model').fill('test-model');
  await ai.getByLabel('API key').fill('test-key');
  await ai.getByRole('button', { name: 'Save AI settings' }).click();

  await ai.getByLabel('Ask Learnitive AI…').fill('Change the greeting to mention Learnitive AI.');
  await ai.getByRole('button', { name: 'Send message' }).click();
  await expect(ai.getByTestId('interactive-ai-proposal')).toBeVisible();
  await expect(page.getByLabel('LaTeX source editor')).toContainText('Hello Learnitive.');

  await ai.getByRole('button', { name: 'Apply', exact: true }).click();
  await expect(page.getByLabel('LaTeX source editor')).toContainText('Hello from Learnitive AI.');
  expect(requestCount).toBe(2);
});
