import { build } from 'esbuild';
import { readFileSync, writeFileSync, copyFileSync, existsSync } from 'fs';
import { join } from 'path';

const SOURCE = join(process.cwd(), 'public', 't.js');
const BACKUP = join(process.cwd(), 'public', 't.source.js');

async function main() {
  if (!existsSync(SOURCE)) {
    console.error(`[build-site-tag] Source not found at ${SOURCE}`);
    process.exit(1);
  }

  const content = readFileSync(SOURCE, 'utf8');
  const lineCount = content.split('\n').length;

  // Skip if already minified
  if (lineCount < 20 && content.includes('Minified production build')) {
    console.log('[build-site-tag] Already minified, skipping');
    return;
  }

  const originalSize = Buffer.byteLength(content);
  console.log(`[build-site-tag] Source: ${(originalSize / 1024).toFixed(1)} KB`);

  // Keep an unminified backup for debugging
  copyFileSync(SOURCE, BACKUP);

  const result = await build({
    entryPoints: [SOURCE],
    minify: true,
    write: false,
    bundle: false,        // t.js is a self-contained IIFE — no imports to resolve
    format: 'iife',
    target: ['es2017'],   // Wide browser support
    legalComments: 'none',
    sourcemap: false,
  });

  if (!result.outputFiles?.[0]) {
    throw new Error('[build-site-tag] esbuild returned no output');
  }

  const minified = result.outputFiles[0].contents;
  const header = `/* meSEO Site Tag • Minified production build */\n`;
  const finalOutput = Buffer.concat([Buffer.from(header), minified]);

  writeFileSync(SOURCE, finalOutput);

  const newSize = finalOutput.length;
  const reduction = ((1 - newSize / originalSize) * 100).toFixed(1);
  console.log(`[build-site-tag] Minified: ${(newSize / 1024).toFixed(1)} KB (${reduction}% reduction)`);
}

main().catch((err) => {
  console.error('[build-site-tag] Build failed:', err);
  process.exit(1);
});
