#!/usr/bin/env node

/**
 * Build script for ba-interactive.html
 *
 * Assembles the HTML template from split source files:
 * - src/template.html (shell with placeholders)
 * - src/styles/*.css (concatenated in alphabetical order)
 * - src/scripts/*.js (concatenated in alphabetical order)
 *
 * Output: ba-interactive.html (single file, compatible with file:// protocol)
 *
 * Preserves template placeholders: {{FEATURE_DATA}}, {{EMBEDDED_ARTIFACTS}}, {{APPLICATION_NAME}}, {{APPLICATION_ID}}
 */

const fs = require('fs');
const path = require('path');

const SRC_DIR = path.join(__dirname, 'src');
const STYLES_DIR = path.join(SRC_DIR, 'styles');
const SCRIPTS_DIR = path.join(SRC_DIR, 'scripts');
const TEMPLATE_FILE = path.join(SRC_DIR, 'template.html');
const OUTPUT_FILE = path.join(__dirname, 'ba-interactive.html');

function readSortedFiles(dir, extension) {
    const files = fs.readdirSync(dir)
        .filter(f => f.endsWith(extension))
        .sort();

    return files.map(f => {
        const content = fs.readFileSync(path.join(dir, f), 'utf8');
        return { name: f, content };
    });
}

function build() {
    console.log('[build-html] Starting build...');

    // Read template
    if (!fs.existsSync(TEMPLATE_FILE)) {
        console.error('[build-html] ERROR: Template not found at', TEMPLATE_FILE);
        process.exit(1);
    }
    let template = fs.readFileSync(TEMPLATE_FILE, 'utf8');

    // Read and concatenate CSS files
    const cssFiles = readSortedFiles(STYLES_DIR, '.css');
    console.log(`[build-html] CSS files: ${cssFiles.map(f => f.name).join(', ')}`);
    const css = cssFiles.map(f => `/* --- ${f.name} --- */\n${f.content}`).join('\n\n');

    // Read and concatenate JS files
    const jsFiles = readSortedFiles(SCRIPTS_DIR, '.js');
    console.log(`[build-html] JS files: ${jsFiles.map(f => f.name).join(', ')}`);
    const js = jsFiles.map(f => `/* --- ${f.name} --- */\n${f.content}`).join('\n\n');

    // Inject into template
    template = template.replace('<!-- CSS_PLACEHOLDER -->', css);
    template = template.replace('<!-- JS_PLACEHOLDER -->', js);

    // Verify placeholders are preserved
    const requiredPlaceholders = ['{{FEATURE_DATA}}', '{{EMBEDDED_ARTIFACTS}}', '{{APPLICATION_NAME}}'];
    const missing = requiredPlaceholders.filter(p => !template.includes(p));
    if (missing.length > 0) {
        console.error('[build-html] ERROR: Missing placeholders:', missing.join(', '));
        process.exit(1);
    }

    // Write output
    fs.writeFileSync(OUTPUT_FILE, template, 'utf8');

    const sizeKB = Math.round(fs.statSync(OUTPUT_FILE).size / 1024);
    console.log(`[build-html] Output: ${OUTPUT_FILE} (${sizeKB} KB)`);
    console.log(`[build-html] CSS: ${cssFiles.length} files, JS: ${jsFiles.length} files`);
    console.log('[build-html] Build complete.');
}

build();
