import { existsSync, readdirSync, statSync } from 'node:fs';
import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
const PEM_EXTENSIONS = new Set(['.pem', '.crt', '.cer']);
export function getGoodVibesRootDir(configManager) {
    const configuredDir = configManager.getControlPlaneConfigDir();
    return resolve(configuredDir);
}
export function getDefaultCertDirectory(configManager) {
    return join(getGoodVibesRootDir(configManager), 'certs');
}
export function getDefaultInboundCertPaths(configManager) {
    const certDir = getDefaultCertDirectory(configManager);
    return {
        certFile: join(certDir, 'fullchain.pem'),
        keyFile: join(certDir, 'privkey.pem'),
    };
}
export function resolvePathFromGoodVibesRoot(value, configManager) {
    const trimmed = value?.trim();
    if (!trimmed)
        return null;
    return isAbsolute(trimmed)
        ? trimmed
        : resolve(getGoodVibesRootDir(configManager), trimmed);
}
export function readPemEntriesFromDirectory(path) {
    if (!existsSync(path))
        return [];
    return readdirSync(path, { withFileTypes: true })
        .filter((entry) => entry.isFile() && PEM_EXTENSIONS.has(extname(entry.name).toLowerCase()))
        .map((entry) => join(path, entry.name))
        .sort((a, b) => a.localeCompare(b));
}
export function isLocalHostname(hostname) {
    const normalized = hostname.trim().toLowerCase();
    return normalized === 'localhost'
        || normalized === '127.0.0.1'
        || normalized === '::1'
        || normalized === '[::1]';
}
export function extractForwardedClientIp(req, trustProxy) {
    if (!trustProxy)
        return undefined;
    const forwarded = req.headers.get('x-forwarded-for');
    if (forwarded) {
        const first = forwarded.split(',').map((value) => value.trim()).find(Boolean);
        if (first)
            return first;
    }
    const realIp = req.headers.get('x-real-ip')?.trim();
    return realIp ? realIp : undefined;
}
export function inspectPrivateKeyPermissions(path) {
    if (!existsSync(path) || process.platform === 'win32') {
        return { available: false };
    }
    const stat = statSync(path);
    const mode = stat.mode & 0o777;
    return {
        available: true,
        safe: (mode & 0o077) === 0,
        mode: `0${mode.toString(8)}`,
    };
}
