import { chromium } from 'playwright';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
 * SuperAssistant Workflow Creator (Demo Script)
 * 
 * This script demonstrates the end-to-end flow:
 * 1. Launch browser with Extension
 * 2. Mock MCP Proxy
 * 3. Simulate user on ChatGPT calling 'n8n_create_workflow'
 */
async function runDemo() {
  const EXTENSION_PATH = path.resolve(__dirname, '../../dist');
  const userDataDir = path.resolve(__dirname, '../../.tmp/demo-user-data');

  console.log('🚀 Starting SuperAssistant Demo...');

  const context = await chromium.launchPersistentContext(userDataDir, {
    headless: false, // Set to true if you don't want to see the browser
    args: [
      `--disable-extensions-except=${EXTENSION_PATH}`,
      `--load-extension=${EXTENSION_PATH}`,
    ],
  });

  // Mock MCP Proxy Tool Call
  await context.route('**/message', async (route) => {
    if (route.request().method() === 'POST') {
      const postData = route.request().postDataJSON();
      if (postData.method === 'tools/call' && postData.params.name === 'n8n_create_workflow') {
        console.log('📦 MCP Proxy intercepted tool call: n8n_create_workflow');
        console.log('📝 Workflow Name:', postData.params.arguments.name);
        
        await route.fulfill({
          json: {
            jsonrpc: '2.0',
            id: postData.id,
            result: {
              success: true,
              workflow: {
                id: 'demo-wf-' + Math.floor(Math.random() * 1000),
                name: postData.params.arguments.name,
                message: 'Successfully created via SuperAssistant!'
              }
            }
          }
        });
        return;
      }
    }
    await route.continue();
  });

  const page = await context.newPage();
  
  console.log('🌐 Navigating to ChatGPT...');
  await page.goto('https://chatgpt.com/', { waitUntil: 'commit' });

  console.log('⏳ Waiting for SuperAssistant to initialize...');
  
  // Wait for the bridge to be available in the page context
  await page.waitForFunction(() => (window as any).__n8nMcpBridge !== undefined, { timeout: 15000 });

  console.log('✅ SuperAssistant Ready!');
  console.log('🤖 Simulating AI calling tool to create workflow...');

  const result = await page.evaluate(async () => {
    const bridge = (window as any).__n8nMcpBridge;
    return await bridge.callTool('n8n_create_workflow', {
      name: 'My New n8n Workflow',
      nodes: [],
      connections: {}
    });
  });

  console.log('🎉 Tool Result:', JSON.stringify(result, null, 2));
  
  if (result.success) {
    console.log('✨ SUCCESS: Workflow created successfully!');
  } else {
    console.error('❌ FAILED: Workflow creation failed.');
  }

  // Keep browser open for a few seconds to see result if not headless
  await page.waitForTimeout(5000);
  await context.close();
}

runDemo().catch(console.error);
