#!/usr/bin/env node

/**
 * This script helps optimize builds on slower CPUs by:
 * 1. Cleaning the .next cache directory to prevent it from growing too large
 * 2. Setting environment variables for optimized builds
 * 3. Clearing node_modules/.cache to prevent stale cache issues
 */

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

// Paths
const rootDir = path.resolve(__dirname, '..');
const nextDir = path.join(rootDir, '.next');
const cacheDir = path.join(rootDir, 'node_modules', '.cache');

console.log('🧹 Cleaning build artifacts for faster build...');

// Clear Next.js cache selectively
if (fs.existsSync(nextDir)) {
  try {
    // Only remove the cache directory, not the entire .next folder
    const cachePath = path.join(nextDir, 'cache');
    if (fs.existsSync(cachePath)) {
      console.log('  Cleaning .next/cache directory...');
      fs.rmSync(cachePath, { recursive: true, force: true });
    }
  } catch (err) {
    console.error('  ❌ Error cleaning .next directory:', err.message);
  }
}

// Clear node_modules/.cache
if (fs.existsSync(cacheDir)) {
  try {
    console.log('  Cleaning node_modules/.cache directory...');
    fs.rmSync(cacheDir, { recursive: true, force: true });
  } catch (err) {
    console.error('  ❌ Error cleaning node_modules/.cache:', err.message);
  }
}

console.log('✅ Cleanup complete!');
console.log('🚀 Starting optimized build process...');

// Build with optimized settings
try {
  execSync('pnpm run build:fast', { 
    stdio: 'inherit',
    env: {
      ...process.env,
      NODE_ENV: 'production',
      NEXT_TELEMETRY_DISABLED: '1',
      NEXT_SKIP_LINT: '1',
      NEXT_SKIP_TS_CHECK: '1',
    }
  });
  console.log('✅ Build completed successfully!');
} catch (err) {
  console.error('❌ Build failed:', err.message);
  process.exit(1);
} 