"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DECISION_END_MARKER = exports.DECISION_START_MARKER = void 0;
exports.extractWorkerDecisionBlockFromText = extractWorkerDecisionBlockFromText;
exports.extractWorkerDecisionBlockFromStructuredOutput = extractWorkerDecisionBlockFromStructuredOutput;
exports.extractPreferredWorkerDecisionBlock = extractPreferredWorkerDecisionBlock;
const branding_1 = require("../core/branding");
exports.DECISION_START_MARKER = `<<<${branding_1.WORKER_DECISION_MARKER_PREFIX}_DECISION_START>>>`;
exports.DECISION_END_MARKER = `<<<${branding_1.WORKER_DECISION_MARKER_PREFIX}_DECISION_END>>>`;
function extractWorkerDecisionBlockFromText(rawOutput) {
    const startIndex = rawOutput.lastIndexOf(exports.DECISION_START_MARKER);
    const endIndex = rawOutput.lastIndexOf(exports.DECISION_END_MARKER);
    if (startIndex === -1 || endIndex === -1 || endIndex <= startIndex) {
        return null;
    }
    return rawOutput
        .slice(startIndex + exports.DECISION_START_MARKER.length, endIndex)
        .trim();
}
function extractWorkerDecisionBlockFromStructuredOutput(rawOutput) {
    return extractWorkerDecisionBlockFromText(decodeStructuredWorkerOutput(rawOutput));
}
function extractPreferredWorkerDecisionBlock(rawOutput) {
    return (extractWorkerDecisionBlockFromStructuredOutput(rawOutput) ??
        extractWorkerDecisionBlockFromText(rawOutput));
}
function decodeStructuredWorkerOutput(rawOutput) {
    const collected = [];
    for (const line of rawOutput.split("\n")) {
        const trimmed = line.trim();
        if (trimmed.length === 0) {
            continue;
        }
        try {
            collectStringValues(JSON.parse(trimmed), collected);
        }
        catch { }
    }
    return collected.join("\n");
}
function collectStringValues(value, collected) {
    if (typeof value === "string") {
        collected.push(value);
        return;
    }
    if (Array.isArray(value)) {
        for (const entry of value) {
            collectStringValues(entry, collected);
        }
        return;
    }
    if (value && typeof value === "object") {
        for (const entry of Object.values(value)) {
            collectStringValues(entry, collected);
        }
    }
}
