#!/usr/bin/env node

/**
 * Bundle Size Check Script
 * 
 * Checks if the plugin bundle size is within the 50KB gzip budget
 * and blocks release if exceeded.
 * 
 * @author Matthew Raymer
 * @version 1.0.0
 */

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

const BUNDLE_SIZE_BUDGET_KB = 50; // 50KB gzip budget (increased for TimeSafari integration)
const DIST_DIR = path.join(__dirname, '..', 'dist');

/**
 * Get gzipped size of a file in KB
 * @param {string} filePath - Path to the file
 * @returns {number} Size in KB
 */
function getGzippedSize(filePath) {
  try {
    const gzipOutput = execSync(`gzip -c "${filePath}" | wc -c`, { encoding: 'utf8' });
    const sizeBytes = parseInt(gzipOutput.trim(), 10);
    return Math.round(sizeBytes / 1024 * 100) / 100; // Round to 2 decimal places
  } catch (error) {
    console.error(`Error getting gzipped size for ${filePath}:`, error.message);
    return 0;
  }
}

/**
 * Check bundle sizes and enforce budget
 */
function checkBundleSizes() {
  console.log('🔍 Checking bundle sizes...');
  
  if (!fs.existsSync(DIST_DIR)) {
    console.error('❌ Dist directory not found. Run "npm run build" first.');
    process.exit(1);
  }

  const filesToCheck = [
    'dist/plugin.js',
    'dist/esm/index.js',
    'dist/web/index.js'
  ];

  let totalSize = 0;
  let budgetExceeded = false;

  for (const file of filesToCheck) {
    const filePath = path.join(__dirname, '..', file);
    
    if (fs.existsSync(filePath)) {
      const size = getGzippedSize(filePath);
      totalSize += size;
      
      console.log(`📦 ${file}: ${size}KB gzipped`);
      
      if (size > BUNDLE_SIZE_BUDGET_KB) {
        console.error(`❌ ${file} exceeds budget: ${size}KB > ${BUNDLE_SIZE_BUDGET_KB}KB`);
        budgetExceeded = true;
      }
    } else {
      console.warn(`⚠️  ${file} not found`);
    }
  }

  console.log(`\n📊 Total bundle size: ${totalSize}KB gzipped`);
  console.log(`🎯 Budget: ${BUNDLE_SIZE_BUDGET_KB}KB gzipped`);

  if (budgetExceeded || totalSize > BUNDLE_SIZE_BUDGET_KB) {
    console.error(`\n❌ Bundle size budget exceeded! Total: ${totalSize}KB > ${BUNDLE_SIZE_BUDGET_KB}KB`);
    console.error('🚫 Release blocked. Please optimize bundle size before releasing.');
    process.exit(1);
  }

  console.log('✅ Bundle size within budget!');
}

// Run the check
checkBundleSizes();
