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: { chainId: 138, rpcUrl: process.env.RPC_URL_138 || process.env.RPC_URL || 'http://127.0.0.1:8545' },
  tezosAdapterAddress: process.env.TEZOS_ADAPTER_ADDRESS || '',
  tezosRpcUrl: process.env.TEZOS_RPC_URL || 'https://mainnet.smartpy.io',
  tezosMinterAddress: process.env.TEZOS_MINTER_ADDRESS || '',
  oraclePrivateKey: resolvePrivateKey(
    process.env.TEZOS_RELAY_ORACLE_KEY,
    process.env.PRIVATE_KEY,
    process.env.DEPLOYER_PRIVATE_KEY,
  ),
  pollIntervalMs: parseInt(process.env.POLL_INTERVAL_MS || '5000', 10),
  maxConcurrent: parseInt(process.env.TEZOS_RELAY_MAX_CONCURRENT || '5', 10),
  mockTezosRelay: process.env.MOCK_TEZOS_RELAY === 'true',
};

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