// storage/sync-log-store.ts — Sync log and conflicts persistence
// Stores sync logs in data/projects/{hash}/spec-sync-log/
import { projectDataDir, readJson, writeJson } from './base-store.js';
import { withFileLock } from './file-mutex.js';
function syncLogPath(projectId) {
    return `${projectDataDir(projectId)}/spec-sync-log/sync-log.json`;
}
function conflictsPath(projectId) {
    return `${projectDataDir(projectId)}/spec-sync-log/conflicts.json`;
}
/**
 * Load sync log entries.
 */
export async function getSyncLog(projectId) {
    return readJson(syncLogPath(projectId), []);
}
/**
 * Append entries to the sync log.
 */
export async function appendSyncLog(projectId, entries) {
    await withFileLock(syncLogPath(projectId), async () => {
        const existing = await readJson(syncLogPath(projectId), []);
        existing.push(...entries);
        // Keep last 500 entries to prevent unbounded growth
        const trimmed = existing.length > 500 ? existing.slice(existing.length - 500) : existing;
        await writeJson(syncLogPath(projectId), trimmed);
    });
}
/**
 * Load active (unresolved) conflicts.
 */
export async function getConflicts(projectId) {
    return readJson(conflictsPath(projectId), []);
}
/**
 * Save conflicts list.
 */
export async function saveConflicts(projectId, conflicts) {
    await withFileLock(conflictsPath(projectId), async () => {
        await writeJson(conflictsPath(projectId), conflicts);
    });
}
/**
 * Add new conflicts (merges with existing unresolved).
 */
export async function addConflicts(projectId, newConflicts) {
    await withFileLock(conflictsPath(projectId), async () => {
        const existing = await readJson(conflictsPath(projectId), []);
        const merged = [...existing, ...newConflicts];
        await writeJson(conflictsPath(projectId), merged);
    });
}
/**
 * Resolve a conflict by ID.
 */
export async function resolveConflict(projectId, conflictId, resolution) {
    return withFileLock(conflictsPath(projectId), async () => {
        const conflicts = await readJson(conflictsPath(projectId), []);
        const conflict = conflicts.find((c) => c.id === conflictId);
        if (!conflict) {
            return null;
        }
        conflict.resolved = true;
        conflict.resolution = resolution;
        await writeJson(conflictsPath(projectId), conflicts);
        return conflict;
    });
}
//# sourceMappingURL=sync-log-store.js.map