/**
 * Chrome Web Store Packaging Script
 * Run: node build_package.js
 * Creates: smart-keywords-pro.zip ready for Chrome Web Store submission
 */
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

// Files/dirs to EXCLUDE from the ZIP package
const EXCLUDE = [
  'patch.py',
  'patch_js.py',
  'patch_lang.py',
  'patch_trial.py',
  'apply_fix.js',
  'update_defaults.js',
  'redesign.js',
  'build_package.js',
  'js/funcs_module.ts',
  '.git',
  '.gitignore',
  'node_modules',
  'package.json',
  'package-lock.json',
  '.antigravityignore',
  '*.zip',
  '_*.js',  // temp scripts
];

const OUTPUT = 'smart-keywords-pro.zip';

// Remove old zip if exists
if (fs.existsSync(OUTPUT)) fs.unlinkSync(OUTPUT);

// Build exclude args for PowerShell Compress-Archive
// Since Compress-Archive doesn't support excludes well, we'll copy to temp then zip
const TEMP = '_build_temp';
if (fs.existsSync(TEMP)) fs.rmSync(TEMP, { recursive: true });
fs.mkdirSync(TEMP);

function shouldExclude(relativePath) {
  for (const pattern of EXCLUDE) {
    if (pattern.startsWith('*')) {
      if (relativePath.endsWith(pattern.slice(1))) return true;
    } else if (relativePath === pattern || relativePath.startsWith(pattern + '/') || relativePath.startsWith(pattern + '\\')) {
      return true;
    }
  }
  return false;
}

function copyRecursive(src, dest) {
  const entries = fs.readdirSync(src, { withFileTypes: true });
  for (const entry of entries) {
    const srcPath = path.join(src, entry.name);
    const destPath = path.join(dest, entry.name);
    const relativePath = path.relative('.', srcPath).replace(/\\/g, '/');

    if (shouldExclude(relativePath) || shouldExclude(entry.name)) continue;

    if (entry.isDirectory()) {
      fs.mkdirSync(destPath, { recursive: true });
      copyRecursive(srcPath, destPath);
    } else {
      fs.copyFileSync(srcPath, destPath);
    }
  }
}

copyRecursive('.', TEMP);

// Create zip using PowerShell
execSync(
  'powershell -Command "Compress-Archive -Path \'' + TEMP + '\\*\' -DestinationPath \'' + OUTPUT + '\' -Force"',
  { stdio: 'inherit' }
);

// Cleanup
fs.rmSync(TEMP, { recursive: true });

const stat = fs.statSync(OUTPUT);
console.log('\n✅ Package created: ' + OUTPUT + ' (' + (stat.size / 1024).toFixed(1) + ' KB)');
console.log('Ready for Chrome Web Store submission!');
