#!/usr/bin/env node
/**
 * Post-build: minify all JS in dist/assets/js/ (static scripts copied from static/assets/js/).
 * Runs after vite build (and optionally after beasties). Uses esbuild for minification.
 */

import * as esbuild from 'esbuild';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.join(__dirname, '..');
const JS_DIR = path.join(ROOT, 'dist', 'assets', 'js');

async function main() {
    if (!fs.existsSync(JS_DIR)) {
        console.warn('dist/assets/js/ not found; skipping static JS minify.');
        return;
    }

    const files = fs.readdirSync(JS_DIR).filter((f) => f.endsWith('.js'));
    if (files.length === 0) {
        console.warn('No .js files in dist/assets/js/; skipping.');
        return;
    }

    for (const file of files) {
        const filePath = path.join(JS_DIR, file);
        const code = fs.readFileSync(filePath, 'utf8');
        const result = await esbuild.transform(code, {
            minify: true,
            target: 'es2015',
        });
        fs.writeFileSync(filePath, result.code, 'utf8');
        console.log('✓ Minified dist/assets/js/' + file);
    }

    console.log('Static JS minify complete.');
}

main().catch((err) => {
    console.error(err);
    process.exit(1);
});
