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

const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Load PRIVATE_KEY from dotenv: smom-dbis-138/.env then service .env
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 = {
  sourceChain: { rpcUrl: process.env.RPC_URL_138 || process.env.RPC_URL || "http://127.0.0.1:8545" },
  etherlinkRpcUrl: process.env.ETHERLINK_RPC_URL || "https://node.mainnet.etherlink.com",
  etherlinkRelayBridge: process.env.ETHERLINK_RELAY_BRIDGE || "",
  relayPrivateKey: resolvePrivateKey(
    process.env.ETHERLINK_RELAY_PRIVATE_KEY,
    process.env.PRIVATE_KEY,
    process.env.DEPLOYER_PRIVATE_KEY,
  ),
  pollIntervalMs: parseInt(process.env.POLL_INTERVAL_MS || "5000", 10),
  maxConcurrent: parseInt(process.env.ETHERLINK_RELAY_MAX_CONCURRENT || "5", 10),
  queueDepthLimit: parseInt(process.env.ETHERLINK_RELAY_QUEUE_DEPTH || "100", 10),
};

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 "";
}
