import { existsSync, readFileSync } from 'fs';
import { join } from 'path';
import { resolvePackageRoot } from './bridge-dir.js';
import { USER_CONFIG_ENV } from './bridge-dir.js';
/** Shipped with npm package (generated at publish from bridge/.env). */
export const BUNDLED_CONFIG_ENV = join(resolvePackageRoot(), 'config.env.defaults');
/** Public production relay (same as app `extra.bridgeUrl`). */
export const DEFAULT_RELAY_URL = 'https://cc.fanpay.online';
export function loadEnvFile(path) {
    if (!existsSync(path))
        return {};
    const out = {};
    for (const line of readFileSync(path, 'utf-8').split('\n')) {
        const t = line.trim();
        if (!t || t.startsWith('#'))
            continue;
        const i = t.indexOf('=');
        if (i < 1)
            continue;
        out[t.slice(0, i).trim()] = t.slice(i + 1).trim();
    }
    return out;
}
function pickNonEmpty(...values) {
    for (const v of values) {
        const t = v?.trim();
        if (t)
            return t;
    }
    return '';
}
/** Relay URL + connector token: bundled defaults → user config → bridge .env → process.env. */
export function resolveRelayConfig(extraPaths = []) {
    const layers = [];
    if (existsSync(BUNDLED_CONFIG_ENV))
        layers.push(loadEnvFile(BUNDLED_CONFIG_ENV));
    for (const p of extraPaths) {
        if (existsSync(p))
            layers.push(loadEnvFile(p));
    }
    if (existsSync(USER_CONFIG_ENV))
        layers.push(loadEnvFile(USER_CONFIG_ENV));
    const merged = {};
    for (const layer of layers)
        Object.assign(merged, layer);
    const relayUrl = pickNonEmpty(merged.RELAY_URL, process.env.RELAY_URL, DEFAULT_RELAY_URL);
    const relayToken = pickNonEmpty(merged.RELAY_TOKEN, process.env.RELAY_TOKEN);
    return { relayUrl, relayToken };
}
