"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveVariables = resolveVariables;
const IS_WIN = process.platform === 'win32';
function shellEscape(s) {
    if (IS_WIN) {
        // cmd.exe / PowerShell: double-quote with internal double-quotes escaped
        return '"' + s.replace(/"/g, '\\"') + '"';
    }
    return "'" + s.replace(/'/g, "'\\''") + "'";
}
function resolveVariables(template, context, mode = 'prompt') {
    let result = template;
    // Built-in variables — escaped in bash mode (ARGUMENTS is user input)
    const argsValue = mode === 'bash' ? shellEscape(context.ARGUMENTS) : context.ARGUMENTS;
    const artifactsValue = mode === 'bash' ? shellEscape(context.ARTIFACTS_DIR) : context.ARTIFACTS_DIR;
    result = result.replaceAll('$ARGUMENTS', argsValue);
    result = result.replaceAll('$ARTIFACTS_DIR', artifactsValue);
    // Node output field access: $node-id.output.fieldName
    result = result.replace(/\$([a-zA-Z0-9_-]+)\.output\.(\w+)/g, (_match, nodeId, field) => {
        const node = context.nodes[nodeId];
        if (!node?.structuredOutput)
            return _match;
        const value = node.structuredOutput[field];
        if (value === undefined)
            return _match;
        const str = String(value);
        return mode === 'bash' ? shellEscape(str) : str;
    });
    // Node raw output: $node-id.output
    result = result.replace(/\$([a-zA-Z0-9_-]+)\.output(?!\.\w)/g, (_match, nodeId) => {
        const node = context.nodes[nodeId];
        if (!node)
            return _match;
        const value = node.output ?? '';
        return mode === 'bash' ? shellEscape(value) : value;
    });
    return result;
}
//# sourceMappingURL=variable-resolver.js.map