import { test, expect, chromium } from '@playwright/test';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const EXTENSION_PATH = path.resolve(__dirname, '../../dist');

test('should find extension ID and test bridge', async () => {
  test.setTimeout(60000);
  const userDataDir = path.resolve(__dirname, '../../.tmp/test-user-data-2');
  
  const context = await chromium.launchPersistentContext(userDataDir, {
    headless: true,
    args: [
      `--disable-extensions-except=${EXTENSION_PATH}`,
      `--load-extension=${EXTENSION_PATH}`,
      '--headless=new',
    ],
  });

  console.log('Browser launched');

  const page = await context.newPage();
  
  // Go to extensions page to see if it's there
  await page.goto('chrome://extensions/');
  console.log('Checking chrome://extensions/');
  
  // Try to find the extension ID
  // In some environments, this page is empty or restricted.
  
  // Plan B: Go to a page that matches and see if it works.
  console.log('Navigating to chatgpt...');
  await page.goto('https://chatgpt.com/', { waitUntil: 'commit' });
  
  // Wait a bit
  await page.waitForTimeout(5000);
  
  const bridgeExists = await page.evaluate(() => (window as any).__n8nMcpBridge !== undefined);
  console.log('Bridge exists on page:', bridgeExists);

  if (bridgeExists) {
    const result = await page.evaluate(async () => {
      return await (window as any).__n8nMcpBridge.callTool('n8n_create_workflow', { name: 'Test' });
    }).catch(e => ({ error: e.message }));
    console.log('Tool call result:', result);
  }

  await context.close();
});
