/**
 * Comprehensive test suite for background window automation functionality
 * Tests the improved behavior with 1280x720 dimensions and automation compatibility
 */

const MCP_HTTP_URL = 'http://localhost:3001/mcp';

async function testBackgroundWindowAutomation() {
  console.log('🧪 Testing Background Window Automation Functionality');
  console.log('====================================================');

  const testCases = [
    {
      name: 'Default 1280x720 background window',
      description: 'Test background window creation with default dimensions',
      params: {
        url: 'https://example.com',
        backgroundPage: true
      },
      expectedWidth: 1280,
      expectedHeight: 720
    },
    {
      name: 'Custom dimensions background window',
      description: 'Test background window with custom dimensions',
      params: {
        url: 'https://httpbin.org/html',
        backgroundPage: true,
        width: 1920,
        height: 1080
      },
      expectedWidth: 1920,
      expectedHeight: 1080
    },
    {
      name: 'Automation-friendly site test',
      description: 'Test with a site that has forms for automation testing',
      params: {
        url: 'https://httpbin.org/forms/post',
        backgroundPage: true,
        width: 1280,
        height: 720
      },
      expectedWidth: 1280,
      expectedHeight: 720
    },
    {
      name: 'Large viewport for complex automation',
      description: 'Test with larger viewport for complex automation scenarios',
      params: {
        url: 'https://www.google.com',
        backgroundPage: true,
        width: 1600,
        height: 900
      },
      expectedWidth: 1600,
      expectedHeight: 900
    }
  ];

  let passedTests = 0;
  let totalTests = testCases.length;

  for (const [index, testCase] of testCases.entries()) {
    console.log(`\n📝 Test ${index + 1}/${totalTests}: ${testCase.name}`);
    console.log(`   Description: ${testCase.description}`);
    console.log(`   URL: ${testCase.params.url}`);
    console.log(`   Expected Dimensions: ${testCase.expectedWidth}x${testCase.expectedHeight}`);
    
    try {
      const response = await fetch(MCP_HTTP_URL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json',
        },
        body: JSON.stringify({
          jsonrpc: '2.0',
          id: Math.random(),
          method: 'tools/call',
          params: {
            name: 'chrome_navigate',
            arguments: testCase.params,
          },
        }),
      });

      const result = await response.json();
      
      if (result.error) {
        console.log(`   ❌ Error: ${result.error.message}`);
      } else if (result.result && result.result.content) {
        const content = JSON.parse(result.result.content[0].text);
        
        // Validate the response
        const validations = [
          { check: content.success === true, name: 'Success flag' },
          { check: content.windowId !== undefined, name: 'Window ID present' },
          { check: content.width === testCase.expectedWidth, name: 'Correct width' },
          { check: content.height === testCase.expectedHeight, name: 'Correct height' },
          { check: content.automationReady === true, name: 'Automation ready flag' },
          { check: content.minimized === true, name: 'Minimized flag' },
          { check: content.tabs && content.tabs.length > 0, name: 'Tab information' },
        ];

        let testPassed = true;
        console.log(`   ✅ Success: ${content.message}`);
        console.log(`   📊 Validation Results:`);
        
        for (const validation of validations) {
          const status = validation.check ? '✅' : '❌';
          console.log(`      ${status} ${validation.name}`);
          if (!validation.check) testPassed = false;
        }

        console.log(`   📋 Response Details:`);
        console.log(`      Window ID: ${content.windowId}`);
        console.log(`      Dimensions: ${content.width}x${content.height}`);
        console.log(`      Tab Count: ${content.tabs?.length || 0}`);
        console.log(`      Automation Ready: ${content.automationReady}`);
        console.log(`      Minimized: ${content.minimized}`);
        
        if (testPassed) {
          passedTests++;
          console.log(`   🎉 Test PASSED`);
        } else {
          console.log(`   💥 Test FAILED - Some validations failed`);
        }
        
        // Wait to observe window behavior
        console.log('   ⏳ Waiting 3 seconds to observe window behavior...');
        await new Promise(resolve => setTimeout(resolve, 3000));
        
      } else {
        console.log(`   ⚠️  Unexpected response format`);
        console.log(`   Raw response:`, JSON.stringify(result, null, 2));
      }
    } catch (error) {
      console.log(`   ❌ Test failed with exception: ${error.message}`);
    }
  }

  console.log('\n🎯 Test Summary');
  console.log('===============');
  console.log(`Tests Passed: ${passedTests}/${totalTests}`);
  console.log(`Success Rate: ${((passedTests / totalTests) * 100).toFixed(1)}%`);
  
  console.log('\n📋 Expected Behavior Checklist:');
  console.log('✓ Window opens with specified dimensions (1280x720 default)');
  console.log('✓ Window appears briefly in normal state');
  console.log('✓ Window minimizes to taskbar after ~1.5 seconds');
  console.log('✓ Web automation tools can interact with minimized window');
  console.log('✓ Window maintains proper viewport dimensions for automation');
  console.log('✓ Response includes automation-ready and minimized flags');
  console.log('✓ Window positioning is consistent (0,0) for automation');
  
  if (passedTests === totalTests) {
    console.log('\n🎉 All tests passed! Background window automation is working correctly.');
  } else {
    console.log('\n⚠️  Some tests failed. Please check the implementation.');
  }
}

// Run the comprehensive test suite
testBackgroundWindowAutomation().catch(console.error);
