// Minimal .env loader (no dependencies).
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const envPath = path.join(__dirname, '..', '.env');

if (fs.existsSync(envPath)) {
  for (const line of fs.readFileSync(envPath, 'utf8').split('\n')) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith('#')) continue;
    const eq = trimmed.indexOf('=');
    if (eq === -1) continue;
    const key = trimmed.slice(0, eq).trim();
    let val = trimmed.slice(eq + 1).trim();
    if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
      val = val.slice(1, -1);
    } else {
      // Strip inline comments on unquoted values: FOO=1  # note → "1"
      val = val.replace(/\s+#.*$/, '').trim();
    }
    if (!(key in process.env)) process.env[key] = val;
  }
}

// Prefer IPv4 for outbound API calls (stable for IP-allowlisted providers).
import dns from 'node:dns';
dns.setDefaultResultOrder('ipv4first');
