// 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) {
    return source.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);
    });
}
//# sourceMappingURL=engine.js.map