"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.DEFAULT_PATHS = void 0;
exports.loadConfig = loadConfig;
exports.writeConfig = writeConfig;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
exports.DEFAULT_PATHS = [
    process.env.APPMINT_HUB_CONFIG,
    '/etc/appmint-hub/config.json',
    path.resolve(process.cwd(), 'config.json'),
].filter(Boolean);
function loadConfig(explicitPath) {
    const found = resolveConfigPath(explicitPath);
    if (!found) {
        const candidates = explicitPath ? [explicitPath, ...exports.DEFAULT_PATHS] : exports.DEFAULT_PATHS;
        throw new Error(`hub-agent: no config found. Looked in: ${candidates.join(', ')}.\n` +
            `Run "hub-agent setup" to generate one, or set APPMINT_HUB_CONFIG.`);
    }
    const raw = fs.readFileSync(found, 'utf-8');
    const cfg = JSON.parse(raw);
    return applyEnvOverrides(applyDefaults(validate(cfg)));
}
/**
 * Persist the current config back to whichever path it was loaded from.
 * Used by the server-driven `update-config` flow so admins can add /
 * remove peripherals from the UI without SSH.
 *
 * Sensitive values (apiKey) are kept on disk in cleartext — the server
 * already stores only the hash; the agent needs the plaintext to auth.
 * File permissions are tightened to 0600 so only the service account reads it.
 */
function writeConfig(cfg, explicitPath) {
    const target = resolveConfigPath(explicitPath) || (explicitPath || exports.DEFAULT_PATHS[0] || '/etc/appmint-hub/config.json');
    fs.mkdirSync(path.dirname(target), { recursive: true });
    fs.writeFileSync(target, JSON.stringify(cfg, null, 2) + '\n', { mode: 0o600 });
    return target;
}
function resolveConfigPath(explicitPath) {
    const candidates = explicitPath ? [explicitPath, ...exports.DEFAULT_PATHS] : exports.DEFAULT_PATHS;
    for (const p of candidates) {
        try {
            if (fs.existsSync(p))
                return p;
        }
        catch {
            // try next
        }
    }
    return null;
}
function validate(cfg) {
    if (!cfg || typeof cfg !== 'object')
        throw new Error('config: not an object');
    if (!cfg.hubName || typeof cfg.hubName !== 'string')
        throw new Error('config.hubName is required');
    if (!cfg.apiKey || typeof cfg.apiKey !== 'string')
        throw new Error('config.apiKey is required');
    if (!cfg.orgId || typeof cfg.orgId !== 'string')
        throw new Error('config.orgId is required');
    if (!cfg.serverUrl || typeof cfg.serverUrl !== 'string')
        throw new Error('config.serverUrl is required');
    if (!Array.isArray(cfg.endpoints))
        cfg.endpoints = [];
    return cfg;
}
function applyDefaults(cfg) {
    return {
        heartbeatMs: 30000,
        reconnectMs: 5000,
        logLevel: 'info',
        ...cfg,
    };
}
function applyEnvOverrides(cfg) {
    if (process.env.APPMINT_HUB_API_KEY)
        cfg.apiKey = process.env.APPMINT_HUB_API_KEY;
    if (process.env.APPMINT_HUB_NAME)
        cfg.hubName = process.env.APPMINT_HUB_NAME;
    if (process.env.APPMINT_HUB_ORGID)
        cfg.orgId = process.env.APPMINT_HUB_ORGID;
    if (process.env.APPMINT_HUB_SERVER)
        cfg.serverUrl = process.env.APPMINT_HUB_SERVER;
    if (process.env.APPMINT_HUB_LOG_LEVEL)
        cfg.logLevel = process.env.APPMINT_HUB_LOG_LEVEL;
    return cfg;
}
//# sourceMappingURL=config.js.map