"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractDraftPayloadFromArgusAnswer = extractDraftPayloadFromArgusAnswer;
exports.extractDraftPayloadFromArgusMetadata = extractDraftPayloadFromArgusMetadata;
exports.extractDraftSecurityConfigPayload = extractDraftSecurityConfigPayload;
function isDraftSecurityConfigPayload(value) {
    return (Boolean(value) &&
        typeof value === 'object' &&
        value.config !== undefined &&
        typeof value.config === 'object');
}
function tryParseDraftPayloadJson(text) {
    const t = String(text || '').trim();
    if (!t.startsWith('{')) {
        return null;
    }
    try {
        const o = JSON.parse(t);
        if (isDraftSecurityConfigPayload(o)) {
            return o;
        }
    }
    catch {
        return null;
    }
    return null;
}
/** Prefer ```json fences; fall back to any fenced block that parses as draft_security_config output. */
function extractDraftPayloadFromArgusAnswer(answer) {
    const a = String(answer || '');
    if (!a.trim()) {
        return null;
    }
    const jsonFenceRe = /```json\s*([\s\S]*?)```/gi;
    let jsonMatch;
    while ((jsonMatch = jsonFenceRe.exec(a)) !== null) {
        const parsed = tryParseDraftPayloadJson(jsonMatch[1] ?? '');
        if (parsed) {
            return parsed;
        }
    }
    const anyFenceRe = /```[a-zA-Z_]*\s*([\s\S]*?)```/g;
    let fenceMatch;
    while ((fenceMatch = anyFenceRe.exec(a)) !== null) {
        const parsed = tryParseDraftPayloadJson(fenceMatch[1] ?? '');
        if (parsed) {
            return parsed;
        }
    }
    const whole = tryParseDraftPayloadJson(a);
    if (whole) {
        return whole;
    }
    return null;
}
/** Tool output is stored on `metadata.apiCalls` when the answer fence JSON is malformed. */
function extractDraftPayloadFromArgusMetadata(metadata) {
    if (!metadata || typeof metadata !== 'object') {
        return null;
    }
    const calls = metadata.apiCalls;
    if (!Array.isArray(calls)) {
        return null;
    }
    for (let i = calls.length - 1; i >= 0; i -= 1) {
        const row = calls[i];
        if (!row || typeof row !== 'object') {
            continue;
        }
        if (row.tool !== 'draft_security_config') {
            continue;
        }
        const blob = row.config;
        if (isDraftSecurityConfigPayload(blob)) {
            return blob;
        }
    }
    return null;
}
function extractDraftSecurityConfigPayload(args) {
    const fromAnswer = args.answer ? extractDraftPayloadFromArgusAnswer(args.answer) : null;
    if (fromAnswer) {
        return fromAnswer;
    }
    return extractDraftPayloadFromArgusMetadata(args.metadata);
}
//# sourceMappingURL=extractDraftSecurityConfigPayload.js.map