/**
 * Minimal JSONL store for offline push messages (app-sent when server was unreachable).
 * These are merged into sync pull responses alongside OpenClaw transcript messages.
 */
import { appendFileSync, existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs";
import { homedir } from "node:os";
import { join, dirname } from "node:path";
import { generateStandaloneServerId } from "./translate.js";
let baseDir = null;
export function setPushStoreBaseDir(dir) {
    baseDir = dir;
}
function resolveBaseDir() {
    if (baseDir)
        return baseDir;
    return join(homedir(), ".openclaw", "friday-next", "sync-push");
}
function pushFilePath(sessionKey) {
    const safe = sessionKey.replace(/[^a-zA-Z0-9._-]/g, "_");
    return join(resolveBaseDir(), `${safe}.jsonl`);
}
export function appendPushMessage(sessionKey, msg) {
    const serverId = generateStandaloneServerId();
    const enriched = { ...msg, serverId };
    const file = pushFilePath(sessionKey);
    mkdirSync(dirname(file), { recursive: true });
    appendFileSync(file, JSON.stringify(enriched) + "\n", "utf-8");
    return serverId;
}
export function readPushMessages(sessionKey) {
    const file = pushFilePath(sessionKey);
    if (!existsSync(file))
        return [];
    const msgs = [];
    const raw = readFileSync(file, "utf-8");
    for (const line of raw.split("\n")) {
        if (!line.trim())
            continue;
        try {
            msgs.push(JSON.parse(line));
        }
        catch {
            // skip corrupt
        }
    }
    return msgs;
}
export function deletePushMessages(sessionKey) {
    const file = pushFilePath(sessionKey);
    try {
        unlinkSync(file);
    }
    catch { /* gone */ }
}
