import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
dotenv.config({ path: path.resolve(__dirname, '../../.env') });
dotenv.config({ path: path.resolve(__dirname, '../.env') });
const cwd = process.cwd();
dotenv.config({ path: path.resolve(cwd, 'smom-dbis-138/.env') });
dotenv.config({ path: path.resolve(cwd, '.env') });

export const config = {
  hubRpcUrl: process.env.RPC_URL_138 || process.env.RPC_URL || 'http://192.168.11.211:8545',
  zedxionRpcUrl: process.env.ZEDXION_MAINNET_RPC || 'https://mainnet-rpc.zedscan.net',
  zedxionCustomBridgeHub: process.env.ZEDXION_CUSTOM_BRIDGE_138 || process.env.ZEDXION_CUSTOM_BRIDGE || '',
  zedxionCustomBridgeDest: process.env.ZEDXION_CUSTOM_BRIDGE_83872 || process.env.ZEDXION_CUSTOM_BRIDGE || '',
  relayPrivateKey: resolvePrivateKey(
    process.env.ZEDXION_RELAY_PRIVATE_KEY,
    process.env.PRIVATE_KEY,
    process.env.DEPLOYER_PRIVATE_KEY,
  ),
  pollIntervalMs: parseInt(process.env.ZEDXION_RELAY_POLL_MS || '6000', 10),
  maxConcurrent: parseInt(process.env.ZEDXION_RELAY_MAX_CONCURRENT || '5', 10),
  queueDepthLimit: parseInt(process.env.ZEDXION_RELAY_QUEUE_DEPTH || '100', 10),
  tokenMapPath: process.env.ZEDXION_TOKEN_MAP || '',
};

function resolvePrivateKey(...candidates) {
  for (const candidate of candidates) {
    if (!candidate) continue;
    const value = candidate.trim();
    if (!value || value.includes('${')) continue;
    if (/^0x[0-9a-fA-F]{64}$/.test(value)) return value;
  }
  return '';
}
