#!/usr/bin/env node

/**
 * Sync VERSION and BUILD_DATE constants in restforge-cli.js from package.json.
 *
 * Called by build-bun.bat before compiling, so the binary's --version output
 * always reflects the current package.json version.
 *
 * Pattern targeted:
 *   const VERSION = '...';
 *   const BUILD_DATE = '...';
 *
 * @module sync-version
 */

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

const TARGET_FILE = path.join(__dirname, 'restforge-cli.js');
const PACKAGE_FILE = path.join(__dirname, 'package.json');

function main() {
    if (!fs.existsSync(PACKAGE_FILE)) {
        console.error('[ERROR] package.json not found:', PACKAGE_FILE);
        process.exit(1);
    }

    if (!fs.existsSync(TARGET_FILE)) {
        console.error('[ERROR] restforge-cli.js not found:', TARGET_FILE);
        process.exit(1);
    }

    const version = require(PACKAGE_FILE).version;
    const buildDate = new Date().toISOString().slice(0, 10);

    if (!version) {
        console.error('[ERROR] Could not read version from package.json');
        process.exit(1);
    }

    let content = fs.readFileSync(TARGET_FILE, 'utf8');
    const before = content;

    const versionPattern = /const VERSION = '[^']*';/;
    const buildDatePattern = /const BUILD_DATE = '[^']*';/;

    if (!versionPattern.test(content)) {
        console.error('[ERROR] VERSION constant pattern not found in restforge-cli.js');
        console.error('        Expected: "const VERSION = \'...\';"');
        process.exit(1);
    }
    if (!buildDatePattern.test(content)) {
        console.error('[ERROR] BUILD_DATE constant pattern not found in restforge-cli.js');
        console.error('        Expected: "const BUILD_DATE = \'...\';"');
        process.exit(1);
    }

    content = content.replace(versionPattern, `const VERSION = '${version}';`);
    content = content.replace(buildDatePattern, `const BUILD_DATE = '${buildDate}';`);

    if (content === before) {
        console.log(`No changes needed: VERSION=${version}, BUILD_DATE=${buildDate} already match.`);
        return;
    }

    fs.writeFileSync(TARGET_FILE, content);
    console.log(`Synced restforge-cli.js: VERSION=${version}, BUILD_DATE=${buildDate}`);
}

main();
