#!/usr/bin/env node
/* Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
 *
 * This file is part of a Moko Consulting project.
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 *
 * FILE INFORMATION
 * DEFGROUP: MokoOnyx.Build
 * INGROUP: MokoOnyx
 * REPO: https://git.mokoconsulting.tech/MokoConsulting/MokoOnyx
 * PATH: /scripts/minify.js
 * VERSION: 01.00.00
 * BRIEF: Minify project CSS and JS assets (excludes vendor/)
 */

const fs = require('fs');
const path = require('path');
const CleanCSS = require('clean-css');
const { minify: terserMinify } = require('terser');

const SRC = path.resolve(__dirname, '..', 'src', 'media');

// Project-owned files only — vendor assets ship pre-minified
const CSS_FILES = [
	'css/editor.css',
	'css/template.css',
	'css/theme/dark.standard.css',
	'css/theme/light.standard.css',
];

const JS_FILES = [
	'js/gtm.js',
	'js/template.js',
];

async function minifyCSS(relPath) {
	const src = path.join(SRC, relPath);
	const dest = src.replace(/\.css$/, '.min.css');
	const input = fs.readFileSync(src, 'utf8');
	const result = new CleanCSS({ level: 1 }).minify(input);

	if (result.errors.length) {
		console.error(`  FAIL ${relPath}:`, result.errors);
		return false;
	}

	fs.writeFileSync(dest, result.styles);
	const ratio = ((1 - result.styles.length / input.length) * 100).toFixed(0);
	console.log(`  ${relPath} → .min.css  (${ratio}% smaller)`);
	return true;
}

async function minifyJS(relPath) {
	const src = path.join(SRC, relPath);
	const dest = src.replace(/\.js$/, '.min.js');
	const input = fs.readFileSync(src, 'utf8');
	const result = await terserMinify(input, { compress: true, mangle: true });

	if (result.error) {
		console.error(`  FAIL ${relPath}:`, result.error);
		return false;
	}

	fs.writeFileSync(dest, result.code);
	const ratio = ((1 - result.code.length / input.length) * 100).toFixed(0);
	console.log(`  ${relPath} → .min.js  (${ratio}% smaller)`);
	return true;
}

async function main() {
	console.log('Minifying project assets...\n');

	let ok = true;

	for (const f of CSS_FILES) {
		if (!await minifyCSS(f)) ok = false;
	}
	for (const f of JS_FILES) {
		if (!await minifyJS(f)) ok = false;
	}

	console.log(ok ? '\nDone.' : '\nCompleted with errors.');
	process.exit(ok ? 0 : 1);
}

main();
