"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadEnv = void 0;
const dotenv_1 = __importDefault(require("dotenv"));
const node_path_1 = __importDefault(require("node:path"));
dotenv_1.default.config();
const optionalString = (value) => {
    const trimmed = value?.trim();
    return trimmed ? trimmed : undefined;
};
const optionalNumber = (value, fallback) => {
    const parsed = Number(value);
    return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
};
const optionalNumberOrUndefined = (value) => {
    const parsed = Number(value);
    return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
};
const requireEnv = (name) => {
    const value = process.env[name];
    if (!value) {
        throw new Error(`Missing required environment variable: ${name}`);
    }
    return value;
};
const loadEnv = () => ({
    telegramBotToken: process.env.TELEGRAM_BOT_TOKEN || requireEnv("BOT_TOKEN"),
    restApiBaseUrl: process.env.REST_API_BASE_URL ?? "http://localhost:5555",
    coinMarketCapApiKey: requireEnv("COINMARKETCAP_API_KEY"),
    storageDir: node_path_1.default.resolve(process.cwd(), process.env.SIGNALS_STORAGE_DIR ?? ".signals-storage"),
    mongoUri: optionalString(process.env.MONGO_URI),
    adminTelegramIds: (process.env.ADMIN_TELEGRAM_IDS ?? "")
        .split(",")
        .map((id) => id.trim())
        .filter(Boolean),
    paymentEncryptionSecret: optionalString(process.env.PAYMENT_ENCRYPTION_SECRET),
    paymentConfirmations: optionalNumber(process.env.PAYMENT_CONFIRMATIONS, 3),
    paymentPollIntervalSeconds: optionalNumber(process.env.PAYMENT_POLL_INTERVAL_SECONDS, 5),
    paymentNetworks: {
        bsc: evmNetwork("BSC", {
            rpcUrl: "",
            usdtAddress: "",
            chainId: 56,
            nativeCurrencySymbol: "BNB",
            nativePriceUsd: 600,
            wrappedNativeAddress: "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",
            swapRouter: "0x10ED43C718714eb63d5aA57B78B54704E256024E",
            swapRouterType: "pancake-v2"
        }),
        base: evmNetwork("BASE", {
            rpcUrl: "",
            usdtAddress: "",
            chainId: 8453,
            nativeCurrencySymbol: "ETH",
            nativePriceUsd: 3000,
            wrappedNativeAddress: "0x4200000000000000000000000000000000000006",
            swapRouter: "0xE592427A0AEce92De3Edee1F18E0157C05861564",
            swapRouterType: "uniswap-v3",
            swapQuoter: "0x61fFE014bA17989E743c5F6cB21bF969dc0bB9aE"
        }),
        avalanche: evmNetwork("AVALANCHE", {
            rpcUrl: "",
            usdtAddress: "",
            chainId: 43114,
            nativeCurrencySymbol: "AVAX",
            nativePriceUsd: 30,
            wrappedNativeAddress: "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",
            swapRouter: "0x60aE616a2155Ee3d9A68541Ba4544862310933d4",
            swapRouterType: "traderjoe-v2"
        }),
        polygon: evmNetwork("POLYGON", {
            rpcUrl: "",
            usdtAddress: "",
            chainId: 137,
            nativeCurrencySymbol: "POL",
            nativePriceUsd: 0.5,
            wrappedNativeAddress: "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",
            swapRouter: "0xE592427A0AEce92De3Edee1F18E0157C05861564",
            swapRouterType: "uniswap-v3",
            swapQuoter: "0x61fFE014bA17989E743c5F6cB21bF969dc0bB9aE"
        }),
        tron: tronNetwork()
    },
    evmVaultAddress: optionalString(process.env.EVM_VAULT_ADDRESS),
    tronVaultAddress: optionalString(process.env.TRON_VAULT_ADDRESS),
    adminRegisterPath: process.env.API_ADMIN_REGISTER_PATH || undefined,
    adminLoginPath: process.env.API_ADMIN_LOGIN_PATH || undefined,
    adminUsername: process.env.ADMIN_USERNAME || process.env.ADMIN_EMAIL || undefined,
    adminEmail: process.env.ADMIN_EMAIL || undefined,
    adminPassword: process.env.ADMIN_PASSWORD || undefined,
    adminName: process.env.ADMIN_NAME ?? "Quant Whisper Admin",
    logLevel: process.env.LOG_LEVEL ?? "info",
    trendingCacheTtlSeconds: optionalNumber(process.env.TRENDING_CACHE_TTL_SECONDS, 120),
    signalsAdminPort: optionalNumberOrUndefined(process.env.SIGNALS_ADMIN_PORT),
    signalsAdminToken: optionalString(process.env.SIGNALS_ADMIN_TOKEN) || optionalString(process.env.ADMIN_PASSWORD),
    jwtSecret: optionalString(process.env.JWT_SECRET),
    twelveDataApiKey: optionalString(process.env.TWELVEDATA_API_KEY),
    supportBotToken: optionalString(process.env.SUPPORT_BOT_TOKEN),
    supportBotUsername: optionalString(process.env.SUPPORT_BOT_USERNAME),
    supportEnabled: process.env.SUPPORT_ENABLED === "true" || process.env.SUPPORT_ENABLED === "1",
    supportAiProvider: optionalString(process.env.SUPPORT_AI_PROVIDER),
    supportAiApiKey: optionalString(process.env.SUPPORT_AI_API_KEY),
    supportAiModel: optionalString(process.env.SUPPORT_AI_MODEL),
    supportAiEndpoint: optionalString(process.env.SUPPORT_AI_ENDPOINT),
    supportAiConfidenceThreshold: optionalNumber(process.env.SUPPORT_AI_CONFIDENCE_THRESHOLD, 0.6),
    keepAliveUrl: optionalString(process.env.KEEP_ALIVE_URL),
    keepAliveIntervalMs: optionalNumber(process.env.KEEP_ALIVE_INTERVAL_MS, 10 * 60 * 1000),
    keepAliveRequestTimeoutMs: optionalNumber(process.env.KEEP_ALIVE_REQUEST_TIMEOUT_MS, 30_000),
    logDir: process.env.LOG_DIR ?? "logs",
    logToFile: process.env.LOG_TO_FILE === "true" || process.env.LOG_TO_FILE === "1"
});
exports.loadEnv = loadEnv;
const evmNetwork = (prefix, defaults) => {
    const rpcUrl = optionalString(process.env[`${prefix}_RPC_URL`]);
    const usdtAddress = optionalString(process.env[`${prefix}_USDT_ADDRESS`]);
    if (!rpcUrl || !usdtAddress)
        return undefined;
    return {
        rpcUrl,
        usdtAddress,
        usdtDecimals: optionalNumberOrUndefined(process.env[`${prefix}_USDT_DECIMALS`]),
        chainId: optionalNumber(process.env[`${prefix}_CHAIN_ID`], defaults.chainId),
        nativeCurrencySymbol: defaults.nativeCurrencySymbol,
        nativePriceUsd: optionalNumber(process.env[`${prefix}_NATIVE_PRICE_USD`], defaults.nativePriceUsd),
        wrappedNativeAddress: optionalString(process.env[`${prefix}_WRAPPED_NATIVE_ADDRESS`]) ?? defaults.wrappedNativeAddress,
        swapRouter: optionalString(process.env[`${prefix}_SWAP_ROUTER`]) ?? defaults.swapRouter,
        swapRouterType: optionalString(process.env[`${prefix}_ROUTER_TYPE`]) ?? defaults.swapRouterType,
        swapQuoter: optionalString(process.env[`${prefix}_SWAP_QUOTER`]) ?? defaults.swapQuoter
    };
};
const tronNetwork = () => {
    const fullHost = optionalString(process.env.TRON_FULL_HOST);
    const usdtContract = optionalString(process.env.TRON_USDT_CONTRACT);
    if (!fullHost || !usdtContract)
        return undefined;
    return {
        fullHost,
        apiKey: optionalString(process.env.TRON_API_KEY),
        usdtContract,
        usdtDecimals: optionalNumberOrUndefined(process.env.TRON_USDT_DECIMALS),
        nativeCurrencySymbol: "TRX",
        nativePriceUsd: optionalNumber(process.env.TRON_NATIVE_PRICE_USD, 0.15),
        swapRouter: optionalString(process.env.TRON_SWAP_ROUTER) ?? "TFrLLXWd9hx9sNJZ3p3TV3pT4zUBfEa48n",
        swapRouterType: "sunswap-v2",
        wrappedNativeAddress: optionalString(process.env.TRON_WRAPPED_NATIVE_ADDRESS) ?? "TNUC4QBXBNUEC7R4ZQW2ZDY5QHJXBSMSLG"
    };
};
