const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

// Set threshold values for each category
const THRESHOLDS = {
  performance: 90,
  accessibility: 90,
  'best-practices': 90,
  seo: 90,
};

async function runLighthouse(url) {
  // Create directory for reports if it doesn't exist
  const reportsDir = path.join(__dirname, 'reports');
  if (!fs.existsSync(reportsDir)) {
    fs.mkdirSync(reportsDir);
  }
  
  // Generate report filename
  const reportPath = path.join(reportsDir, `lighthouse-report-${Date.now()}.json`);
  
  try {
    // Run Lighthouse using CLI
    const command = `npx lighthouse "${url}" --output=json --output-path="${reportPath}" --only-categories=performance,accessibility,best-practices,seo --form-factor=desktop --throttling-method=simulate --screenEmulation.mobile=false`;
    
    execSync(command, { stdio: 'inherit' });
    
    // Read and parse the report
    const report = JSON.parse(fs.readFileSync(reportPath, 'utf8'));
    
    console.log('\nLighthouse Results:');
    console.log('--------------------');
    
    // Process and display results
    let allPassed = true;
    Object.keys(THRESHOLDS).forEach(category => {
      const score = Math.round(report.categories[category].score * 100);
      const threshold = THRESHOLDS[category];
      const passed = score >= threshold;
      
      if (!passed) {
        allPassed = false;
      }
      
      console.log(`${category}: ${score}/100 - ${passed ? 'PASS' : 'FAIL'} (Threshold: ${threshold})`);
    });
    
    // Display audits that failed
    console.log('\nFailed Audits:');
    console.log('--------------');
    let hasFailedAudits = false;
    
    Object.values(report.audits).forEach(audit => {
      if (audit.score !== null && audit.score < 0.9) {
        hasFailedAudits = true;
        console.log(`- ${audit.title}: ${Math.round(audit.score * 100)}/100`);
        console.log(`  ${audit.description}`);
      }
    });
    
    if (!hasFailedAudits) {
      console.log('No significant audit failures!');
    }
    
    console.log(`\nDetailed report saved to: ${reportPath}`);
    
    return allPassed;
  } catch (error) {
    console.error('Error running Lighthouse:', error);
    return false;
  }
}

// URL to test - this should be your local server address
const url = process.argv[2] || 'http://localhost:8080';

// Start the tests
console.log(`Starting Lighthouse tests on ${url}`);

runLighthouse(url)
  .then(passed => {
    console.log(`\nOverall: ${passed ? 'PASSED' : 'FAILED'}`);
    process.exit(passed ? 0 : 1);
  })
  .catch(error => {
    console.error('Error running Lighthouse:', error);
    process.exit(1);
  }); 