/**
 * Configuration management for RPC Translator
 */

import dotenv from 'dotenv';

dotenv.config();

export interface Config {
  server: {
    httpPort: number;
    wsPort: number;
    nodeEnv: string;
  };
  besu: {
    httpUrls: string[];
    wsUrls: string[];
    chainId: number;
  };
  web3signer: {
    url: string;
    timeout: number;
  };
  redis: {
    host: string;
    port: number;
    password?: string;
    db: number;
    keyPrefix: string;
  };
  vault: {
    addr: string;
    roleId?: string;
    secretId?: string;
    translatorConfigPath: string;
  };
  policy: {
    walletAllowlist: string[];
    maxGasLimit: bigint;
    maxGasPriceWei: bigint;
    minGasPriceWei: bigint;
  };
  allowPrivateNetworkMethods: boolean;
}

function parseStringArray(value: string | undefined, separator: string = ','): string[] {
  if (!value) return [];
  return value.split(separator).map(s => s.trim()).filter(s => s.length > 0);
}

function parseBigInt(value: string | undefined, defaultValue: bigint): bigint {
  if (!value) return defaultValue;
  try {
    return BigInt(value);
  } catch {
    return defaultValue;
  }
}

export function loadConfig(): Config {
  const walletAllowlistEnv = process.env.WALLET_ALLOWLIST;
  
  return {
    server: {
      httpPort: parseInt(process.env.HTTP_PORT || '9545', 10),
      wsPort: parseInt(process.env.WS_PORT || '9546', 10),
      nodeEnv: process.env.NODE_ENV || 'production',
    },
    besu: {
      httpUrls: parseStringArray(process.env.BESU_HTTP_URLS),
      wsUrls: parseStringArray(process.env.BESU_WS_URLS),
      chainId: parseInt(process.env.CHAIN_ID || '138', 10),
    },
    web3signer: {
      url: process.env.WEB3SIGNER_URL || 'http://localhost:9000',
      timeout: parseInt(process.env.WEB3SIGNER_TIMEOUT || '5000', 10),
    },
    redis: {
      host: process.env.REDIS_HOST || 'localhost',
      port: parseInt(process.env.REDIS_PORT || '6379', 10),
      password: process.env.REDIS_PASSWORD || undefined,
      db: parseInt(process.env.REDIS_DB || '0', 10),
      keyPrefix: process.env.REDIS_KEY_PREFIX || 'rpc-translator:138',
    },
    vault: {
      addr: process.env.VAULT_ADDR || 'http://localhost:8200',
      roleId: process.env.VAULT_ROLE_ID || undefined,
      secretId: process.env.VAULT_SECRET_ID || undefined,
      translatorConfigPath: process.env.VAULT_PATH_TRANSLATOR_CONFIG || 'secret/data/chain138/translator',
    },
    policy: {
      walletAllowlist: parseStringArray(walletAllowlistEnv),
      maxGasLimit: parseBigInt(process.env.MAX_GAS_LIMIT, BigInt(30000000)),
      maxGasPriceWei: parseBigInt(process.env.MAX_GAS_PRICE_WEI, BigInt('100000000000')),
      minGasPriceWei: parseBigInt(process.env.MIN_GAS_PRICE_WEI, BigInt('1000000000')),
    },
    allowPrivateNetworkMethods: process.env.ALLOW_PRIVATE_NETWORK_METHODS !== 'false', // Default: true
  };
}
