#!/usr/bin/env node

/**
 * Bundle Analysis Script
 * Run after build to analyze bundle size and performance
 */

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

const NEXT_DIR = path.join(__dirname, '../.next');
const BUILD_MANIFEST = path.join(NEXT_DIR, 'build-manifest.json');

console.log('\n🔍 Analyzing bundle size...\n');

if (!fs.existsSync(BUILD_MANIFEST)) {
  console.error('❌ Build manifest not found. Run `npm run build` first.');
  process.exit(1);
}

const manifest = JSON.parse(fs.readFileSync(BUILD_MANIFEST, 'utf-8'));

// Analyze pages
const pages = manifest.pages || {};
const sortedPages = Object.entries(pages)
  .map(([route, files]) => {
    const size = files.reduce((total, file) => {
      const filePath = path.join(NEXT_DIR, file);
      if (fs.existsSync(filePath)) {
        return total + fs.statSync(filePath).size;
      }
      return total;
    }, 0);
    return { route, size, files: files.length };
  })
  .sort((a, b) => b.size - a.size);

// Display results
console.log('📦 Page Bundle Sizes:\n');
console.log('Route                                Size      Files');
console.log('─'.repeat(60));

sortedPages.slice(0, 10).forEach(({ route, size, files }) => {
  const sizeKB = (size / 1024).toFixed(2);
  const routeDisplay = route.padEnd(35);
  const sizeDisplay = `${sizeKB} KB`.padStart(10);
  console.log(`${routeDisplay} ${sizeDisplay}  ${files}`);
});

// Calculate totals
const totalSize = sortedPages.reduce((sum, { size }) => sum + size, 0);
const avgSize = totalSize / sortedPages.length;

console.log('─'.repeat(60));
console.log(`Total: ${(totalSize / 1024 / 1024).toFixed(2)} MB`);
console.log(`Average: ${(avgSize / 1024).toFixed(2)} KB per page`);
console.log(`Pages: ${sortedPages.length}`);

// Performance recommendations
console.log('\n💡 Performance Recommendations:\n');

if (avgSize > 500 * 1024) {
  console.log('⚠️  Average page size > 500KB - Consider code splitting');
}

const largePages = sortedPages.filter(({ size }) => size > 1024 * 1024);
if (largePages.length > 0) {
  console.log(`⚠️  ${largePages.length} page(s) > 1MB - Review large dependencies`);
}

const totalPages = sortedPages.length;
if (totalPages > 100) {
  console.log('⚠️  Large number of pages - Ensure proper ISR/SSG strategy');
}

if (avgSize < 200 * 1024 && totalSize < 5 * 1024 * 1024) {
  console.log('✅ Bundle size is well optimized!');
}

console.log('\n📊 Run `npm run build` to see detailed Next.js stats\n');
