"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSessionsDir = getSessionsDir;
exports.ensureSessionsDir = ensureSessionsDir;
exports.getSessionPath = getSessionPath;
exports.readSession = readSession;
exports.writeSession = writeSession;
exports.fingerprintComments = fingerprintComments;
exports.shouldCompress = shouldCompress;
exports.summarizeWithRunner = summarizeWithRunner;
exports.truncateFallback = truncateFallback;
exports.buildCompressedContext = buildCompressedContext;
const fs = __importStar(require("node:fs"));
const path = __importStar(require("node:path"));
const crypto = __importStar(require("node:crypto"));
const logger_1 = require("./logger");
function getSessionsDir() {
    return path.join(process.cwd(), '.aidev', 'sessions');
}
function ensureSessionsDir() {
    const dir = getSessionsDir();
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
    }
}
function sanitizeTaskId(taskId) {
    return taskId.replace(/[^a-zA-Z0-9_.-]/g, '_');
}
function getSessionPath(taskId) {
    return path.join(getSessionsDir(), `${sanitizeTaskId(taskId)}.json`);
}
function readSession(taskId) {
    const file = getSessionPath(taskId);
    if (!fs.existsSync(file))
        return null;
    try {
        const raw = fs.readFileSync(file, 'utf8');
        const parsed = JSON.parse(raw);
        if (parsed &&
            typeof parsed.taskId === 'string' &&
            typeof parsed.fingerprint === 'string' &&
            typeof parsed.summary === 'string') {
            return parsed;
        }
        return null;
    }
    catch {
        return null;
    }
}
function writeSession(taskId, data) {
    ensureSessionsDir();
    fs.writeFileSync(getSessionPath(taskId), JSON.stringify(data, null, 2), 'utf8');
}
function fingerprintComments(comments) {
    const hash = crypto.createHash('sha256');
    for (const c of comments) {
        hash.update(c.id);
        hash.update('\0');
        hash.update(c.text);
        hash.update('\0');
    }
    return hash.digest('hex');
}
function shouldCompress(prompt, threshold) {
    return prompt.length > threshold;
}
function buildRawContext(comments) {
    if (comments.length === 0)
        return '';
    return ('\n\nConversation context:\n' +
        comments.map((c) => `${c.author}: ${c.text}`).join('\n'));
}
async function summarizeWithRunner(comments, runners) {
    const conversation = comments.map((c) => `${c.author}: ${c.text}`).join('\n');
    const prompt = 'Summarize the following conversation. Preserve any decisions, dev notes, dropped requirements, and open questions. Keep it concise (<1000 words). Output only the summary, no preamble.\n\n' +
        conversation;
    for (const runner of runners) {
        if (!runner.isAvailable())
            continue;
        try {
            const result = await runner.run(prompt);
            if (result.success && result.output.trim()) {
                return result.output.trim();
            }
            logger_1.logger.warn(`Summarization runner ${runner.name} returned no output`);
        }
        catch (err) {
            logger_1.logger.warn(`Summarization runner ${runner.name} failed: ${err.message}`);
        }
    }
    return null;
}
function truncateFallback(comments) {
    const text = comments.map((c) => `${c.author}: ${c.text}`).join('\n');
    if (text.length <= 3000)
        return text;
    return text.slice(0, 1500) + '\n…\n' + text.slice(-1500);
}
async function buildCompressedContext(comments, taskId, runners, config) {
    if (!config.autoCompress || comments.length <= 1) {
        return buildRawContext(comments);
    }
    const raw = buildRawContext(comments);
    if (!shouldCompress(raw, config.compressThreshold)) {
        return raw;
    }
    const lastComment = comments[comments.length - 1];
    const earlier = comments.slice(0, -1);
    const fingerprint = fingerprintComments(earlier);
    let summary;
    const cached = readSession(taskId);
    if (cached && cached.fingerprint === fingerprint && cached.summary) {
        summary = cached.summary;
    }
    else {
        const runnerSummary = await summarizeWithRunner(earlier, runners);
        if (runnerSummary) {
            summary = runnerSummary;
        }
        else {
            logger_1.logger.warn('Auto-compress: no runner produced a summary; using deterministic truncation');
            summary = truncateFallback(earlier);
        }
        writeSession(taskId, {
            taskId,
            updatedAt: Date.now(),
            fingerprint,
            summary,
            lastCommentId: lastComment.id,
        });
    }
    return ('\n\nSummary of earlier conversation (auto-compressed):\n' +
        summary +
        '\n\nLatest comment:\n' +
        `${lastComment.author}: ${lastComment.text}`);
}
//# sourceMappingURL=sessions.js.map