import { readFileSync, writeFileSync, appendFileSync, mkdirSync, existsSync } from 'node:fs';
import { atomicWriteFileSync } from '../utils/atomic-write.js';
import { join } from 'node:path';
import { config } from '../config.js';
import { logger } from '../utils/logger.js';
function getQueuesDir() {
    return join(config.session.dataDir, 'queues');
}
function getQueueFile(rootMessageId) {
    return join(getQueuesDir(), `${rootMessageId}.jsonl`);
}
function getOffsetFile(rootMessageId) {
    return join(getQueuesDir(), `${rootMessageId}.offset`);
}
export function ensureQueue(rootMessageId) {
    const dir = getQueuesDir();
    if (!existsSync(dir)) {
        mkdirSync(dir, { recursive: true });
    }
    const queueFile = getQueueFile(rootMessageId);
    if (!existsSync(queueFile)) {
        writeFileSync(queueFile, '', 'utf-8');
    }
}
export function appendMessage(rootMessageId, message) {
    ensureQueue(rootMessageId);
    const line = JSON.stringify(message) + '\n';
    appendFileSync(getQueueFile(rootMessageId), line, 'utf-8');
    logger.debug(`MessageQueue: appended message to ${rootMessageId}`);
}
function readOffset(rootMessageId) {
    const offsetFile = getOffsetFile(rootMessageId);
    if (!existsSync(offsetFile))
        return 0;
    try {
        return parseInt(readFileSync(offsetFile, 'utf-8').trim(), 10) || 0;
    }
    catch {
        return 0;
    }
}
function writeOffset(rootMessageId, offset) {
    // 原子写：offset 半截（如 "12" 只写出 "1"）会导致重启后消息重读或跳读。
    atomicWriteFileSync(getOffsetFile(rootMessageId), String(offset));
}
/** Reset offset to re-read all messages from a given byte position (0 = beginning). */
export function rewindOffset(rootMessageId, to = 0) {
    writeOffset(rootMessageId, to);
}
/** Return the current read offset (byte position) without advancing it. */
export function getOffset(rootMessageId) {
    return readOffset(rootMessageId);
}
export function readUnread(rootMessageId) {
    const queueFile = getQueueFile(rootMessageId);
    if (!existsSync(queueFile))
        return [];
    const content = readFileSync(queueFile, 'utf-8');
    const offset = readOffset(rootMessageId);
    if (offset >= content.length)
        return [];
    const unread = content.slice(offset);
    const messages = [];
    for (const line of unread.split('\n')) {
        if (line.trim()) {
            try {
                messages.push(JSON.parse(line));
            }
            catch {
                logger.warn(`MessageQueue: failed to parse line: ${line}`);
            }
        }
    }
    if (messages.length > 0) {
        writeOffset(rootMessageId, content.length);
    }
    return messages;
}
//# sourceMappingURL=message-queue.js.map