import * as fs from "node:fs";
import * as path from "node:path";
import * as crypto from "node:crypto";
import * as os from "node:os";
const CONFIG_DIR = path.join(os.homedir(), ".agentgazer");
const CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
const DB_FILE = path.join(CONFIG_DIR, "data.db");
export function getConfigDir() {
    return CONFIG_DIR;
}
export function getConfigPath() {
    return CONFIG_FILE;
}
export function getDbPath() {
    return DB_FILE;
}
function generateToken() {
    return crypto.randomBytes(32).toString("hex");
}
/**
 * Migrate old flat config to new hierarchical structure.
 * Returns true if migration was performed.
 */
function migrateConfig(parsed) {
    const config = { token: parsed.token };
    let migrated = false;
    // Check for old flat structure
    const hasOldFormat = typeof parsed.port === "number" ||
        typeof parsed.proxyPort === "number" ||
        typeof parsed.autoOpen === "boolean" ||
        typeof parsed.retentionDays === "number";
    if (hasOldFormat) {
        migrated = true;
        // Migrate to new structure
        if (typeof parsed.port === "number" || typeof parsed.proxyPort === "number" || typeof parsed.autoOpen === "boolean") {
            config.server = {};
            if (typeof parsed.port === "number")
                config.server.port = parsed.port;
            if (typeof parsed.proxyPort === "number")
                config.server.proxyPort = parsed.proxyPort;
            if (typeof parsed.autoOpen === "boolean")
                config.server.autoOpen = parsed.autoOpen;
        }
        if (typeof parsed.retentionDays === "number") {
            config.data = { retentionDays: parsed.retentionDays };
        }
    }
    else {
        // Already new format or fresh config
        if (parsed.server && typeof parsed.server === "object") {
            config.server = parsed.server;
        }
        if (parsed.data && typeof parsed.data === "object") {
            config.data = parsed.data;
        }
    }
    // Alerts config (new, no migration needed)
    if (parsed.alerts && typeof parsed.alerts === "object") {
        config.alerts = parsed.alerts;
    }
    // Providers
    if (parsed.providers && typeof parsed.providers === "object") {
        config.providers = parsed.providers;
    }
    return { config, migrated };
}
export function ensureConfig() {
    // Create directory if it doesn't exist
    if (!fs.existsSync(CONFIG_DIR)) {
        fs.mkdirSync(CONFIG_DIR, { recursive: true });
    }
    // Read existing config or create new one
    const existing = readConfig();
    if (existing) {
        return existing;
    }
    const config = {
        token: generateToken(),
    };
    fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), "utf-8");
    return config;
}
export function readConfig() {
    if (!fs.existsSync(CONFIG_FILE)) {
        return null;
    }
    try {
        const raw = fs.readFileSync(CONFIG_FILE, "utf-8");
        const parsed = JSON.parse(raw);
        if (typeof parsed.token === "string" && parsed.token.length > 0) {
            const { config, migrated } = migrateConfig(parsed);
            // Write back if migrated
            if (migrated) {
                saveConfig(config);
            }
            return config;
        }
        return null;
    }
    catch {
        return null;
    }
}
export function saveConfig(config) {
    if (!fs.existsSync(CONFIG_DIR)) {
        fs.mkdirSync(CONFIG_DIR, { recursive: true });
    }
    fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), "utf-8");
}
export function setProvider(name, providerConfig) {
    const config = ensureConfig();
    if (!config.providers) {
        config.providers = {};
    }
    config.providers[name] = providerConfig;
    saveConfig(config);
    return config;
}
export function removeProvider(name) {
    const config = ensureConfig();
    if (config.providers) {
        delete config.providers[name];
        if (Object.keys(config.providers).length === 0) {
            delete config.providers;
        }
    }
    saveConfig(config);
    return config;
}
export function listProviders() {
    const config = readConfig();
    return config?.providers ?? {};
}
export function resetToken() {
    const existing = readConfig();
    const config = {
        ...existing,
        token: generateToken(),
    };
    saveConfig(config);
    return config;
}
// ---------------------------------------------------------------------------
// Helper functions for accessing config values with defaults
// ---------------------------------------------------------------------------
export function getServerPort(config) {
    return config?.server?.port ?? 18800;
}
export function getProxyPort(config) {
    return config?.server?.proxyPort ?? 18900;
}
export function getAutoOpen(config) {
    return config?.server?.autoOpen ?? true;
}
export function getRetentionDays(config) {
    return config?.data?.retentionDays ?? 30;
}
export function getAlertDefaults(config) {
    return config?.alerts?.defaults ?? {};
}
export function updateAlertDefaults(defaults) {
    const config = ensureConfig();
    if (!config.alerts) {
        config.alerts = {};
    }
    config.alerts.defaults = {
        ...config.alerts.defaults,
        ...defaults,
    };
    saveConfig(config);
    return config;
}
//# sourceMappingURL=config.js.map