// ==========================================
// Chat Switchboard — CM6 Build Script
// ==========================================
// Bundles CodeMirror 6 into a single IIFE that
// exposes window.CM. Run via scripts/build-editor.sh
// or directly: node build.mjs [--outdir=path]
//
// Output:
//   codemirror.bundle.js  (~295KB min, ~90KB gzip)
//   codemirror.bundle.css (~5-10KB)
// ==========================================

import { build } from 'esbuild';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));

// Parse --outdir=<path> from argv
let outdir = resolve(__dirname, 'dist');
for (const arg of process.argv.slice(2)) {
    if (arg.startsWith('--outdir=')) {
        outdir = resolve(arg.slice('--outdir='.length));
    }
}

try {
    const result = await build({
        entryPoints: [resolve(__dirname, 'index.mjs')],
        bundle: true,
        minify: true,
        format: 'iife',
        target: ['es2020'],
        outfile: resolve(outdir, 'codemirror.bundle.js'),
        // Metafile for optional size analysis
        metafile: true,
        // Log level
        logLevel: 'info',
    });

    // Print bundle size summary
    if (result.metafile) {
        const outputs = result.metafile.outputs;
        for (const [file, info] of Object.entries(outputs)) {
            const kb = (info.bytes / 1024).toFixed(1);
            console.log(`  ${file}: ${kb} KB`);
        }
    }

    console.log(`✅ CM6 bundle → ${outdir}`);
} catch (err) {
    console.error('❌ CM6 build failed:', err.message);
    process.exit(1);
}
