/**
 * Validates that the built-in functions registry has no duplicate keys.
 * 
 * This script parses the functionsRegistry.js file and checks for duplicate property names
 * in the exported object, which would cause silent overrides in JavaScript.
 * 
 * Usage: node tools/validate-builtins.js
 * Exit code 0 = validation passed, 1 = duplicates found
 */

import * as fs from "fs";
import * as path from "path";

import { fileURLToPath } from "url";
import { dirname } from "path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const BUILTINS_FILE = path.join(__dirname, '..', 'core', 'src', 'builtins', 'functionsRegistry.js');

function validateBuiltins() {
    const content = fs.readFileSync(BUILTINS_FILE, 'utf8');
    
    // Extract property keys from the object literal
    // Pattern: property_name: { (optionally with quotes)
    const keyPattern = /^\s*['"]?([A-Z_][A-Z0-9_]*)['"]?\s*:\s*\{/gm;
    
    const keys = [];
    const duplicates = new Map();
    const lineNumbers = new Map();
    
    // Split into lines to track line numbers
    const lines = content.split('\n');
    
    lines.forEach((line, index) => {
        const match = line.match(/^\s*['"]?([A-Z_][A-Z0-9_]*)['"]?\s*:\s*\{/);
        if (match) {
            const key = match[1];
            const lineNum = index + 1; // 1-based line numbers
            
            if (keys.includes(key)) {
                if (!duplicates.has(key)) {
                    duplicates.set(key, [lineNumbers.get(key)]);
                }
                duplicates.get(key).push(lineNum);
            } else {
                keys.push(key);
                lineNumbers.set(key, lineNum);
            }
        }
    });
    
    if (duplicates.size > 0) {
        console.error('❌ Duplicate keys found in built-ins registry:\n');
        
        for (const [key, lines] of duplicates) {
            console.error(`  "${key}" appears ${lines.length} times:`);
            lines.forEach(line => {
                console.error(`    - Line ${line}`);
            });
            console.error('');
        }
        
        console.error('⚠️  JavaScript object literals silently override earlier keys with later ones.');
        console.error('   Please consolidate these duplicate entries.\n');
        
        return false;
    }
    
    console.log(`✓ Built-ins validation passed: ${keys.length} unique functions, no duplicates`);
    return true;
}

// Run validation
const isValid = validateBuiltins();
process.exit(isValid ? 0 : 1);
