import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import { randomBytes } from 'node:crypto';
const CONFIG_DIR = join(homedir(), '.ocr-provenance-mcp');
const CONFIG_FILE = 'wrapper.json';
const DEFAULTS = {
    imageTag: 'latest',
    httpPort: 3366,
    dashboardPort: 3367,
};
export function getConfigPath() {
    return join(CONFIG_DIR, CONFIG_FILE);
}
export function loadConfig() {
    const configPath = getConfigPath();
    if (!existsSync(configPath)) {
        return { ...DEFAULTS };
    }
    try {
        const raw = readFileSync(configPath, 'utf-8');
        const parsed = JSON.parse(raw);
        return {
            ...DEFAULTS,
            ...parsed,
        };
    }
    catch {
        // Corrupted config file -- return defaults and let the user know
        process.stderr.write(`Warning: Could not parse ${configPath}, using defaults.\n`);
        return { ...DEFAULTS };
    }
}
export function saveConfig(config) {
    if (!existsSync(CONFIG_DIR)) {
        mkdirSync(CONFIG_DIR, { recursive: true });
    }
    const configPath = getConfigPath();
    // Atomic write: write to temp file, then rename
    const tmpPath = configPath + '.' + randomBytes(4).toString('hex') + '.tmp';
    writeFileSync(tmpPath, JSON.stringify(config, null, 2) + '\n', 'utf-8');
    renameSync(tmpPath, configPath);
}
export function getConfigValue(key) {
    const config = loadConfig();
    const normalizedKey = normalizeKey(key);
    if (normalizedKey === 'licenseKey')
        return config.licenseKey;
    if (normalizedKey === 'imageTag')
        return config.imageTag;
    if (normalizedKey === 'httpPort')
        return config.httpPort?.toString();
    if (normalizedKey === 'dashboardPort')
        return config.dashboardPort?.toString();
    if (normalizedKey === 'extraEnv') {
        return config.extraEnv ? JSON.stringify(config.extraEnv) : undefined;
    }
    return undefined;
}
export function setConfigValue(key, value) {
    const config = loadConfig();
    const normalizedKey = normalizeKey(key);
    if (normalizedKey === 'licenseKey') {
        config.licenseKey = value;
    }
    else if (normalizedKey === 'imageTag') {
        config.imageTag = value;
    }
    else if (normalizedKey === 'httpPort') {
        const port = parseInt(value, 10);
        if (isNaN(port) || port < 1 || port > 65535) {
            throw new Error(`Invalid port number: ${value}. Must be 1-65535.`);
        }
        config.httpPort = port;
    }
    else if (normalizedKey === 'dashboardPort') {
        const port = parseInt(value, 10);
        if (isNaN(port) || port < 1 || port > 65535) {
            throw new Error(`Invalid port number: ${value}. Must be 1-65535.`);
        }
        config.dashboardPort = port;
    }
    else {
        throw new Error(`Unknown config key: ${key}. Valid keys: license_key, image_tag, http_port, dashboard_port`);
    }
    saveConfig(config);
}
/**
 * Normalize user-facing config keys (snake_case, kebab-case) to camelCase property names.
 */
function normalizeKey(key) {
    const map = {
        license_key: 'licenseKey',
        licensekey: 'licenseKey',
        'license-key': 'licenseKey',
        licenseKey: 'licenseKey',
        image_tag: 'imageTag',
        imagetag: 'imageTag',
        'image-tag': 'imageTag',
        imageTag: 'imageTag',
        tag: 'imageTag',
        http_port: 'httpPort',
        httpport: 'httpPort',
        'http-port': 'httpPort',
        httpPort: 'httpPort',
        port: 'httpPort',
        dashboard_port: 'dashboardPort',
        dashboardport: 'dashboardPort',
        'dashboard-port': 'dashboardPort',
        dashboardPort: 'dashboardPort',
        extra_env: 'extraEnv',
        extraenv: 'extraEnv',
        'extra-env': 'extraEnv',
        extraEnv: 'extraEnv',
    };
    return map[key] ?? key;
}
//# sourceMappingURL=config.js.map