function isRecord(value) {
    return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isTraversable(value) {
    return Array.isArray(value) || isRecord(value);
}
export class ResponseBlacklistSanitizer {
    cfg;
    criticalPaths = new Set([
        'status',
        'output',
        'output_text',
        'required_action',
        'choices[].message.content',
        'choices[].message.tool_calls',
        'choices[].finish_reason'
    ]);
    constructor(config) {
        this.cfg = config;
    }
    isCritical(pathStr) {
        if (!this.cfg.keepCritical) {
            return false;
        }
        return this.criticalPaths.has(pathStr);
    }
    unwrapPayload(payload) {
        if (!isRecord(payload)) {
            return {};
        }
        const rootCandidate = payload.data;
        return isRecord(rootCandidate) ? rootCandidate : payload;
    }
    deleteByPath(obj, pathStr) {
        const tokens = pathStr.split('.');
        const recurse = (current, idx) => {
            if (!isTraversable(current) || idx >= tokens.length) {
                return;
            }
            const token = tokens[idx];
            const isArrayWildcard = token.endsWith('[]');
            const key = isArrayWildcard ? token.slice(0, -2) : token;
            if (idx === tokens.length - 1) {
                if (!isArrayWildcard && isRecord(current) && Object.prototype.hasOwnProperty.call(current, key)) {
                    delete current[key];
                }
                return;
            }
            if (isArrayWildcard) {
                if (isRecord(current)) {
                    const arr = current[key];
                    if (Array.isArray(arr)) {
                        for (const item of arr) {
                            recurse(item, idx + 1);
                        }
                    }
                }
            }
            else if (isRecord(current)) {
                recurse(current[key], idx + 1);
            }
        };
        recurse(obj, 0);
    }
    apply(payload) {
        const out = isRecord(payload) ? payload : {};
        try {
            const root = this.unwrapPayload(out);
            const configPaths = Array.isArray(this.cfg?.paths) ? this.cfg.paths ?? [] : [];
            for (const p of configPaths) {
                if (typeof p !== 'string' || !p) {
                    continue;
                }
                if (this.isCritical(p)) {
                    continue;
                }
                this.deleteByPath(root, p);
            }
            return out;
        }
        catch {
            return out;
        }
    }
}
