import { Buffer } from 'node:buffer';
import { getSensitivePathRefusal, verifyPreservedFragments, shouldBypassLeanMode, } from './compression-guards.js';
const DEFAULT_MAX_BYTES = 200_000;
function byteLength(value) {
    return Buffer.byteLength(value, 'utf-8');
}
function compressParagraph(paragraph) {
    if (paragraph.startsWith('```') ||
        paragraph.startsWith('~~~') ||
        paragraph.startsWith('- [') ||
        /`[^`\n]+`|\bSPEC-\d+\b|\bhttps?:\/\//.test(paragraph)) {
        return paragraph;
    }
    return paragraph
        .split('\n')
        .map((line) => line.replace(/\s+/g, ' ').trim())
        .filter(Boolean)
        .join(' ');
}
export function compressSafeContext(input) {
    const originalBytes = byteLength(input.content);
    if (input.sourcePath) {
        const refusal = getSensitivePathRefusal(input.sourcePath);
        if (refusal) {
            return {
                ok: false,
                originalBytes,
                compressedBytes: originalBytes,
                refusedReason: refusal,
                preservedChecks: [],
            };
        }
    }
    if (originalBytes > (input.maxBytes ?? DEFAULT_MAX_BYTES)) {
        return {
            ok: false,
            originalBytes,
            compressedBytes: originalBytes,
            refusedReason: `Refusing content over ${String(input.maxBytes ?? DEFAULT_MAX_BYTES)} bytes`,
            preservedChecks: [],
        };
    }
    if (input.flow && shouldBypassLeanMode(input.flow)) {
        return {
            ok: true,
            originalBytes,
            compressedBytes: originalBytes,
            preservedChecks: ['bypass-sensitive-flow'],
            content: input.content,
        };
    }
    const compressed = input.content
        .split(/\n{2,}/)
        .map((paragraph) => compressParagraph(paragraph.trim()))
        .filter(Boolean)
        .join('\n\n');
    const preserved = verifyPreservedFragments(input.content, compressed);
    if (!preserved.ok) {
        return {
            ok: false,
            originalBytes,
            compressedBytes: byteLength(compressed),
            refusedReason: `Compression would drop preserved fragment: ${preserved.checks[0] ?? 'unknown'}`,
            preservedChecks: preserved.checks,
        };
    }
    return {
        ok: true,
        originalBytes,
        compressedBytes: byteLength(compressed),
        preservedChecks: preserved.checks,
        content: compressed,
    };
}
//# sourceMappingURL=safe-context-compressor.js.map