import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
function sortWatchers(watchers) {
    return [...watchers].sort((a, b) => a.label.localeCompare(b.label) || a.id.localeCompare(b.id));
}
export function getWatcherStorePath(rootPath) {
    return join(rootPath, '.goodvibes', 'goodvibes', 'watchers.json');
}
export function resolveWatcherStorePath(storePath) {
    if (!storePath) {
        throw new Error('Watcher store requires an explicit storePath');
    }
    return storePath;
}
export function loadWatcherSnapshot(storePath) {
    return loadWatcherSnapshotFromPath(storePath);
}
export function loadWatcherSnapshotFromPath(storePath) {
    if (!existsSync(storePath))
        return null;
    try {
        const raw = readFileSync(storePath, 'utf-8');
        const parsed = JSON.parse(raw);
        if (!parsed || parsed.version !== 1 || !Array.isArray(parsed.watchers))
            return null;
        return {
            version: 1,
            watchers: parsed.watchers.filter((record) => Boolean(record && typeof record.id === 'string')),
        };
    }
    catch {
        return null;
    }
}
export function saveWatcherSnapshot(watchers, storePath) {
    saveWatcherSnapshotToPath(watchers, storePath);
}
export function saveWatcherSnapshotToPath(watchers, storePath) {
    mkdirSync(dirname(storePath), { recursive: true });
    const snapshot = {
        version: 1,
        watchers: sortWatchers(watchers),
    };
    writeFileSync(storePath, `${JSON.stringify(snapshot, null, 2)}\n`, 'utf-8');
}
