import { getKeptTailTokenEstimate } from "./compaction-boundary.js";
import { reconstructCompactedTranscript, validateDeletedRanges } from "./deleted-ranges.js";
import { planDeletedLineRanges } from "./range-planner.js";
/** Calculate the single global line threshold directly from the prepared setting. */
export function targetKeepLines(preparation) {
    const protectedLines = preparation.region.protectedLineNumbers?.size ?? 0;
    return Math.max(protectedLines, Math.round(preparation.region.lines.length * preparation.parameters.compression_ratio));
}
function withWholeContextStats(result, preparation) {
    const tokensAfter = result.stats.tokensAfter + getKeptTailTokenEstimate(preparation);
    const percentReduction = preparation.tokensBefore === 0
        ? 0
        : Math.round((1 - tokensAfter / preparation.tokensBefore) * 1000) / 10;
    return {
        ...result,
        rung: "planned",
        stats: { ...result.stats, tokensBefore: preparation.tokensBefore, tokensAfter, percentReduction },
    };
}
/** Execute one whole-region model plan and mechanically accept its safe deletions. */
export async function runVerbatimCompaction(preparation, model, apiKey, headers, signal, thinkingLevel, options) {
    if (signal?.aborted)
        throw new Error("Compaction cancelled");
    const raw = await planDeletedLineRanges(preparation.region, preparation.parameters, model, { apiKey, headers }, signal, thinkingLevel, preparation.settings.reserveTokens, targetKeepLines(preparation), { streamFn: options.streamFn, sessionFilePath: options.sessionFilePath });
    if (signal?.aborted)
        throw new Error("Compaction cancelled");
    return withWholeContextStats(reconstructCompactedTranscript(preparation.region, validateDeletedRanges(raw, preparation.region)), preparation);
}
//# sourceMappingURL=compaction-runner.js.map