const fs = require('fs');
const path = require('path');

const stepsDir = path.join(__dirname, '../test-results/step-verification');

console.log('='.repeat(80));
console.log('STEP-BY-STEP API CALL ANALYSIS');
console.log('='.repeat(80));
console.log();

for (let i = 1; i <= 5; i++) {
  const stepDir = path.join(stepsDir, `step-${i}`);
  const apiFile = path.join(stepDir, 'api-calls.json');
  const wsFile = path.join(stepDir, 'ws-messages.json');

  if (!fs.existsSync(apiFile)) {
    console.log(`Step ${i}: No data captured (step not completed)`);
    console.log();
    continue;
  }

  const apiCalls = JSON.parse(fs.readFileSync(apiFile, 'utf-8'));
  const wsMessages = JSON.parse(fs.readFileSync(wsFile, 'utf-8'));

  const requests = apiCalls.filter(c => c.type === 'request');
  const uniqueEndpoints = new Set();

  requests.forEach(r => {
    try {
      const url = new URL(r.url);
      uniqueEndpoints.add(`${r.method} ${url.pathname}`);
    } catch (e) {
      // Skip invalid URLs
    }
  });

  console.log(`STEP ${i}:`);
  console.log(`  Total API requests: ${requests.length}`);
  console.log(`  Unique endpoints: ${uniqueEndpoints.size}`);
  console.log(`  WebSocket messages: ${wsMessages.length}`);
  console.log();
  console.log('  Unique API endpoints called:');

  Array.from(uniqueEndpoints).forEach(endpoint => {
    const count = requests.filter(r => {
      try {
        const url = new URL(r.url);
        return `${r.method} ${url.pathname}` === endpoint;
      } catch (e) {
        return false;
      }
    }).length;
    console.log(`    ${endpoint}${count > 1 ? ` (${count} times)` : ''}`);
  });

  console.log();
  console.log('-'.repeat(80));
  console.log();
}
