/**
 * Per-device sync sequence tracking.
 * Stored in ~/.openclaw/friday-next/sync-state.json
 */
import { mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs";
import { homedir } from "node:os";
import { dirname } from "node:path";
let statePath = null;
let stateCache = null;
export function setSyncStatePath(path) {
    statePath = path;
    stateCache = null;
}
function resolvePath() {
    if (statePath)
        return statePath;
    statePath = `${homedir()}/.openclaw/friday-next/sync-state.json`;
    return statePath;
}
function loadState() {
    if (stateCache)
        return stateCache;
    const path = resolvePath();
    try {
        if (existsSync(path)) {
            stateCache = JSON.parse(readFileSync(path, "utf-8"));
            return stateCache;
        }
    }
    catch {
        // corrupted — reset
    }
    stateCache = {};
    return stateCache;
}
function saveState() {
    const path = resolvePath();
    mkdirSync(dirname(path), { recursive: true });
    writeFileSync(path, JSON.stringify(stateCache ?? {}, null, 2), "utf-8");
}
export function getLastSyncSeq(deviceId) {
    const state = loadState();
    return state[deviceId.trim().toUpperCase()] ?? 0;
}
export function setLastSyncSeq(deviceId, seq) {
    const state = loadState();
    state[deviceId.trim().toUpperCase()] = seq;
    saveState();
}
/** Vitest-only: reset in-memory cache and path. */
export function resetSyncStateForTest() {
    statePath = null;
    stateCache = null;
}
