import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { ConfigManager } from '../../config/manager.js';
import { CONFIG_SCHEMA } from '../../config/index.js';
export function getConfigControlPlaneDir(configManager) {
    return configManager.getControlPlaneConfigDir();
}
function getSettingsControlPath(configDir) {
    return join(configDir, 'settings-sync.json');
}
export function defaultStore() {
    return {
        version: 2,
        events: [],
        managedLocks: [],
        failures: [],
        syncedSettings: [],
        managedSettings: [],
        conflicts: [],
        rollbackHistory: [],
    };
}
function migrateStore(raw) {
    if (!raw || typeof raw !== 'object')
        return defaultStore();
    const store = raw;
    if (store.version === 2) {
        return {
            ...defaultStore(),
            ...store,
            events: Array.isArray(store.events) ? store.events : [],
            managedLocks: Array.isArray(store.managedLocks) ? store.managedLocks : [],
            failures: Array.isArray(store.failures) ? store.failures : [],
            syncedSettings: Array.isArray(store.syncedSettings) ? store.syncedSettings : [],
            managedSettings: Array.isArray(store.managedSettings) ? store.managedSettings : [],
            conflicts: Array.isArray(store.conflicts) ? store.conflicts : [],
            rollbackHistory: Array.isArray(store.rollbackHistory) ? store.rollbackHistory : [],
        };
    }
    return {
        ...defaultStore(),
        events: Array.isArray(store.events) ? store.events : [],
        managedLocks: Array.isArray(store.managedLocks) ? store.managedLocks : [],
        failures: Array.isArray(store.failures) ? store.failures : [],
    };
}
export function readStore(configDir) {
    try {
        return migrateStore(JSON.parse(readFileSync(getSettingsControlPath(configDir), 'utf-8')));
    }
    catch {
        return defaultStore();
    }
}
export function writeStore(store, configDir) {
    const path = getSettingsControlPath(configDir);
    mkdirSync(dirname(path), { recursive: true });
    writeFileSync(path, `${JSON.stringify(store, null, 2)}\n`, 'utf-8');
}
export function trimStore(store) {
    return {
        ...store,
        events: store.events.slice(-60),
        failures: store.failures.slice(-20),
        conflicts: store.conflicts.slice(-40),
        rollbackHistory: store.rollbackHistory.slice(-20),
    };
}
export function configSnapshot(configManager) {
    const snapshot = {};
    for (const entry of CONFIG_SCHEMA) {
        snapshot[entry.key] = structuredClone(configManager.get(entry.key));
    }
    return snapshot;
}
export function sourcePriority(source) {
    switch (source) {
        case 'managed': return 3;
        case 'synced': return 2;
        case 'local': return 1;
        case 'default': return 0;
    }
}
export function inferRisk(changes) {
    if (changes.some((change) => change.key.startsWith('danger.') || change.key.startsWith('permissions.') || change.key.startsWith('sandbox.'))) {
        return 'high';
    }
    if (changes.some((change) => change.key.startsWith('provider.') || change.key.startsWith('storage.') || change.key.startsWith('orchestration.'))) {
        return 'medium';
    }
    return 'low';
}
export function makeRollbackToken() {
    return `managed-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
export function toLayerRecord(key, value, source, sourceLabel, detail, path, locked) {
    return {
        key,
        value: structuredClone(value),
        source,
        sourceLabel,
        detail,
        ...(path ? { path } : {}),
        updatedAt: Date.now(),
        ...(locked ? { locked: true } : {}),
    };
}
