"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TRUSYS_RESULT_PREFIX = void 0;
exports.parseProviderResponseFromExecution = parseProviderResponseFromExecution;
exports.TRUSYS_RESULT_PREFIX = '__TRUSYS_RESULT__';
function parseProviderResponseFromExecution(execution) {
    const stdout = execution?.stdout ?? '';
    const stderr = execution?.stderr ?? '';
    const status = (execution?.status ?? '').toLowerCase();
    if (status && status !== 'success' && status !== 'succeeded') {
        return {
            output: '',
            error: stderr || stdout || `Execution status: ${status}`,
        };
    }
    const markerIndex = stdout.lastIndexOf(exports.TRUSYS_RESULT_PREFIX);
    if (markerIndex === -1) {
        return {
            output: '',
            error: stderr ||
                `Provider did not emit ${exports.TRUSYS_RESULT_PREFIX} in stdout. stdout=${stdout.slice(0, 500)}`,
        };
    }
    const jsonPart = stdout.slice(markerIndex + exports.TRUSYS_RESULT_PREFIX.length).trim();
    try {
        const parsed = JSON.parse(jsonPart);
        if (parsed?.error) {
            return parsed;
        }
        if (typeof parsed?.output === 'undefined') {
            return {
                output: '',
                error: 'Provider result JSON must include an "output" field',
            };
        }
        return parsed;
    }
    catch (err) {
        return {
            output: '',
            error: `Failed to parse provider result JSON: ${err instanceof Error ? err.message : String(err)}`,
        };
    }
}
//# sourceMappingURL=parseExecutionResult.js.map