// Copyright (c) 2026 Modelware. All rights reserved.
import { bindTemplateParameters } from './binder.js';
export function renderTemplate(template, invocation) {
    const bound = bindTemplateParameters(template, invocation.context, invocation.args);
    const output = interpolateTemplateBody(template.body, bound.values);
    return {
        output,
        values: bound.values,
    };
}
export function interpolateTemplateBody(source, values) {
    // First pass: resolve function calls like ${ontology(member)}
    const afterFunctions = source.replace(/\$\{([a-zA-Z][a-zA-Z0-9]*)\(([A-Za-z_][A-Za-z0-9_]*)\)\}/g, (_match, funcName, argKey) => {
        if (!(argKey in values)) {
            return _match;
        }
        const argValue = values[argKey];
        if (typeof argValue !== 'string' || !argValue) {
            return _match;
        }
        const result = applyTemplateFunction(funcName, argValue);
        return result ?? _match;
    });
    // Second pass: resolve simple param references like ${member}
    return afterFunctions.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?:\|([^|}]*)(?:\|([^}]*))?)?\}/g, (_match, key, delimiter, entryTemplate) => {
        if (!(key in values)) {
            return _match;
        }
        const value = values[key];
        if (Array.isArray(value)) {
            const format = (entry) => entryTemplate ? entryTemplate.replace('%s', entry) : entry;
            return value.map((entry) => format(String(entry))).join(delimiter ?? ', ');
        }
        if (value === null || value === undefined) {
            return '';
        }
        if (typeof value === 'object') {
            return JSON.stringify(value);
        }
        return String(value);
    });
}
function applyTemplateFunction(funcName, arg) {
    if (funcName === 'ontology') {
        const hashIndex = arg.lastIndexOf('#');
        return hashIndex > 0 ? arg.substring(0, hashIndex) : undefined;
    }
    return undefined;
}
//# sourceMappingURL=engine.js.map