#!/usr/bin/env bun
/**
 * Quick test tool to open Playwright in non-headless mode with proxy
 * For debugging and manual testing of the IB website
 */
import { Browser } from '@stock-bot/browser';

async function testProxyBrowser() {
  try {
    console.log('🚀 Starting proxy browser test...');

    // Initialize browser in non-headless mode
    await Browser.initialize({
      headless: false, // Non-headless for debugging
      timeout: 30000, // 30 second timeout
      blockResources: false, // Allow all resources
    });
    console.log('✅ Browser initialized in non-headless mode');

    // Create page with your proxy
    const { page } = await Browser.createPageWithProxy(
      'https://www.interactivebrokers.com/en/trading/products-exchanges.php#/',
      'http://doimvbnb-US-rotate:w5fpiwrb9895@p.webshare.io:80'
    );
    console.log('✅ Page created with proxy');

    // Set up network event logging to see what's happening
    page.onNetworkEvent(event => {
      if (event.type === 'request') {
        console.log('📤 Request:', {
          url: event.url,
          method: event.method,
          data: event.requestData,
          headers: Object.keys(event.headers || {}).length,
        });
      }

      if (event.type === 'response') {
        console.log('📥 Response:', {
          url: event.url,
          status: event.status,
        });
      }
    });

    console.log('⏳ Waiting for page load...');
    await page.waitForLoadState('domcontentloaded', { timeout: 30000 });
    console.log('✅ Page loaded - you can now interact with it manually');

    // Log current URL
    const currentUrl = page.url();
    console.log('🌐 Current URL:', currentUrl);

    // Keep the browser open for manual testing
    console.log('🔍 Browser is open for manual testing...');
    console.log('💡 You can now:');
    console.log('   - Click around the page manually');
    console.log('   - Check if the proxy is working');
    console.log('   - Test the Products tab and radio buttons');
    console.log('   - Press Ctrl+C to close when done');

    // Wait indefinitely until user closes
    await new Promise(resolve => {
      process.on('SIGINT', () => {
        console.log('👋 Closing browser...');
        resolve(void 0);
      });
    });
  } catch (error) {
    console.error('❌ Proxy browser test failed:', { error });
  } finally {
    try {
      await Browser.close();
      console.log('🧹 Browser cleanup completed');
    } catch (cleanupError) {
      console.error('Failed to cleanup browser:', { error: cleanupError });
    }
  }
}

// Run the test
if (import.meta.main) {
  testProxyBrowser().catch(console.error);
}

export { testProxyBrowser };
