function escapeInert(text) {
    return text.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function redact(text, patterns) {
    return patterns.reduce((current, pattern) => {
        const re = new RegExp(pattern, 'gi');
        return current.replace(re, '[redacted]');
    }, text);
}
function uniqueLines(lines) {
    return [...new Set(lines)];
}
function failureLines(lines) {
    const failures = lines.filter((line) => /\b(error|fail|failed|exception|critical)\b/i.test(line));
    return failures.length > 0 ? failures : lines;
}
function jsonSummary(text) {
    try {
        const parsed = JSON.parse(text);
        if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
            return [`JSON object keys: ${Object.keys(parsed).join(', ')}`];
        }
        if (Array.isArray(parsed)) {
            return [`JSON array length: ${String(parsed.length)}`];
        }
    }
    catch {
        // Fall through to normal line handling.
    }
    return text.split('\n');
}
function selectStrategy(input) {
    const strategy = input.policy.outputs.strategies[input.kind] ?? input.policy.outputs.strategies.generic;
    if (strategy === undefined) {
        throw new Error('Token waste policy must define outputs.strategies.generic');
    }
    return strategy;
}
function compactLines(input, strategy) {
    const rawLines = strategy.summarizeKeys === true ? jsonSummary(input.text) : input.text.split('\n');
    const selected = strategy.keepFailures === true ? failureLines(rawLines) : rawLines;
    const unique = strategy.uniqueOnly === true ? uniqueLines(selected) : selected;
    return unique.slice(0, strategy.maxLines);
}
export function filterVerboseOutput(input) {
    const strategy = selectStrategy(input);
    const originalLines = input.text.split('\n').length;
    const lines = compactLines(input, strategy);
    const compact = redact(escapeInert(lines.join('\n')), input.policy.redaction.redactPatterns);
    const decisions = [
        {
            decision: originalLines > lines.length ? 'summarize' : 'include',
            target: input.kind,
            reason: `Applied policy output strategy for ${input.kind}.`,
            evidence: [{ source: 'policy', key: `outputs.strategies.${input.kind}` }],
            confidence: input.policy.outputs.strategies[input.kind] !== undefined ? 'high' : 'medium',
        },
    ];
    return {
        text: compact,
        originalLines,
        returnedLines: lines.length,
        ...(input.fullOutputRef !== undefined ? { fullOutputRef: input.fullOutputRef } : {}),
        decisions,
    };
}
//# sourceMappingURL=output-filter.js.map