import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs';
import { join } from 'path';
import { homedir, hostname } from 'os';
import { randomUUID } from 'crypto';
const CONFIG_DIR = join(homedir(), '.shieldcortex');
const CONFIG_FILE = join(CONFIG_DIR, 'config.json');
const DEFAULT_BASE_URL = 'https://api.shieldcortex.ai';
// Cache to avoid repeated file reads
let cachedConfig = null;
export function getCloudConfig() {
    if (cachedConfig)
        return cachedConfig;
    try {
        if (!existsSync(CONFIG_FILE)) {
            return { cloudApiKey: null, cloudBaseUrl: DEFAULT_BASE_URL, cloudEnabled: false };
        }
        const raw = JSON.parse(readFileSync(CONFIG_FILE, 'utf-8'));
        cachedConfig = {
            cloudApiKey: raw.cloudApiKey ?? null,
            cloudBaseUrl: raw.cloudBaseUrl ?? DEFAULT_BASE_URL,
            cloudEnabled: raw.cloudEnabled ?? false,
        };
        return cachedConfig;
    }
    catch {
        return { cloudApiKey: null, cloudBaseUrl: DEFAULT_BASE_URL, cloudEnabled: false };
    }
}
export function setCloudConfig(updates) {
    let existing = {};
    try {
        if (existsSync(CONFIG_FILE)) {
            existing = JSON.parse(readFileSync(CONFIG_FILE, 'utf-8'));
        }
    }
    catch {
        // Start fresh if parse fails
    }
    if (updates.cloudApiKey !== undefined)
        existing.cloudApiKey = updates.cloudApiKey;
    if (updates.cloudBaseUrl !== undefined)
        existing.cloudBaseUrl = updates.cloudBaseUrl;
    if (updates.cloudEnabled !== undefined)
        existing.cloudEnabled = updates.cloudEnabled;
    mkdirSync(CONFIG_DIR, { recursive: true });
    writeFileSync(CONFIG_FILE, JSON.stringify(existing, null, 2) + '\n');
    // Invalidate cache
    cachedConfig = null;
}
/** Reset the in-memory cache (useful for testing) */
export function clearCloudConfigCache() {
    cachedConfig = null;
}
// ── Trusted Skills ──────────────────────────────────────
export function readRawConfig() {
    try {
        if (existsSync(CONFIG_FILE)) {
            return JSON.parse(readFileSync(CONFIG_FILE, 'utf-8'));
        }
    }
    catch { /* ignore */ }
    return {};
}
function writeRawConfig(raw) {
    mkdirSync(CONFIG_DIR, { recursive: true });
    writeFileSync(CONFIG_FILE, JSON.stringify(raw, null, 2) + '\n');
    cachedConfig = null;
}
export function getTrustedSkills() {
    const raw = readRawConfig();
    return Array.isArray(raw.trustedSkills) ? raw.trustedSkills : [];
}
export function addTrustedSkill(path) {
    const raw = readRawConfig();
    const list = Array.isArray(raw.trustedSkills) ? raw.trustedSkills : [];
    if (!list.includes(path)) {
        list.push(path);
        raw.trustedSkills = list;
        writeRawConfig(raw);
    }
}
export function removeTrustedSkill(path) {
    const raw = readRawConfig();
    const list = Array.isArray(raw.trustedSkills) ? raw.trustedSkills : [];
    const idx = list.indexOf(path);
    if (idx !== -1) {
        list.splice(idx, 1);
        raw.trustedSkills = list;
        writeRawConfig(raw);
    }
}
// ── Sync Timestamp ────────────────────────────────────
/**
 * Write lastSyncAt timestamp to config.json on successful cloud sync.
 */
export function updateLastSyncAt() {
    const raw = readRawConfig();
    raw.lastSyncAt = new Date().toISOString();
    writeRawConfig(raw);
}
// ── Device Identity ────────────────────────────────────
/**
 * Returns a stable UUID for this machine.
 * Generates and persists on first call; reads from config thereafter.
 */
export function getDeviceId() {
    const raw = readRawConfig();
    if (typeof raw.deviceId === 'string' && raw.deviceId) {
        return raw.deviceId;
    }
    const id = randomUUID();
    raw.deviceId = id;
    writeRawConfig(raw);
    return id;
}
/**
 * Returns the OS hostname for this machine.
 * Stores in config on first call; reads from config thereafter.
 */
export function getDeviceName() {
    const raw = readRawConfig();
    if (typeof raw.deviceName === 'string' && raw.deviceName) {
        return raw.deviceName;
    }
    const name = hostname();
    raw.deviceName = name;
    writeRawConfig(raw);
    return name;
}
//# sourceMappingURL=config.js.map