import fs from 'fs-extra';
import { readJsonFile, writeJsonFile } from '../lib/json.js';
import { getStatePath } from '../lib/paths.js';
const SYNC_STATE_REL_PATH = 'data/catalog/sync-state.json';
export function getSyncStatePath() {
    return getStatePath(SYNC_STATE_REL_PATH);
}
const EMPTY_STATE = { registries: {} };
export async function loadSyncState() {
    const syncStatePath = getSyncStatePath();
    if (!(await fs.pathExists(syncStatePath))) {
        return EMPTY_STATE;
    }
    const raw = await readJsonFile(syncStatePath);
    if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
        return EMPTY_STATE;
    }
    const registries = raw.registries;
    return { registries: registries ?? {} };
}
export async function saveSyncState(state) {
    await writeJsonFile(getSyncStatePath(), state);
}
export function getUpdatedSince(state, registryId) {
    return state.registries[registryId]?.lastUpdatedSince;
}
export function setUpdatedSince(state, registryId, timestamp) {
    return {
        registries: {
            ...state.registries,
            [registryId]: {
                ...(state.registries[registryId] ?? {}),
                lastUpdatedSince: timestamp
            }
        }
    };
}
export function setSuccessfulSync(state, registryId, timestamp) {
    return {
        registries: {
            ...state.registries,
            [registryId]: {
                ...(state.registries[registryId] ?? {}),
                lastSuccessfulSyncAt: timestamp
            }
        }
    };
}
export function getStaleRegistries(state, now = new Date(), staleAfterHours = 48) {
    const staleCutoffMs = now.getTime() - staleAfterHours * 60 * 60 * 1000;
    return Object.entries(state.registries)
        .filter(([, value]) => {
        if (!value.lastSuccessfulSyncAt) {
            return true;
        }
        const stamp = Date.parse(value.lastSuccessfulSyncAt);
        return !Number.isFinite(stamp) || stamp < staleCutoffMs;
    })
        .map(([registryId]) => registryId)
        .sort((a, b) => a.localeCompare(b));
}
