import { SessionStorage } from "../session/sessionStorage.js";
import { RollingSummary } from "./rollingSummary.js";
export function compactSessionTranscript(dataDir, sessionId, keepTail = 12) {
    const records = new SessionStorage(dataDir, sessionId).readAll(1000);
    const chatMessages = records
        .filter((record) => record.role === "user" || record.role === "assistant" || record.role === "system")
        .map((record) => ({
        role: record.role === "user" ? "user" : record.role === "assistant" ? "assistant" : "system",
        content: record.text,
    }));
    const rolling = new RollingSummary();
    rolling.absorb(chatMessages, keepTail);
    return {
        sessionId,
        totalRecords: records.length,
        summarizedRecords: Math.max(0, records.length - keepTail),
        tailRecords: records.slice(-keepTail),
        summary: rolling.text,
    };
}
export function formatSessionCompactSummary(summary) {
    return [
        `session: ${summary.sessionId}`,
        `records: total=${summary.totalRecords} summarized=${summary.summarizedRecords} tail=${summary.tailRecords.length}`,
        "summary:",
        summary.summary.trim() || "(not enough transcript records to compact)",
        "tail:",
        ...summary.tailRecords.map((record) => `${record.role}: ${firstLine(record.text)}`),
    ].join("\n");
}
function firstLine(value) {
    const line = value.split(/\r?\n/)[0]?.trim() ?? "";
    return line.length > 160 ? `${line.slice(0, 157)}...` : line;
}
