// Daemons (whatsapp, cron, heartbeat) run as their own Node processes and do
// NOT inherit Next.js's automatic .env.local loading. Without this, the
// orchestrator's ANTHROPIC_API_KEY check in lib/whatsapp-agent.js fails and
// every inbound WhatsApp message falls back to the keyword-routed canned
// reply. Call this once at the top of each daemon entry point before any
// runtime module is imported.
//
// Node 22.5+ ships process.loadEnvFile natively — no dotenv dependency needed.
import path from 'node:path';

export function loadProjectEnv() {
  if (typeof process.loadEnvFile !== 'function') return { loaded: false, reason: 'unsupported_node' };
  const candidates = [
    process.env.MADARX_ENV_FILE,
    path.join(process.cwd(), '.env.local'),
    path.join(process.cwd(), '.env'),
  ].filter(Boolean);
  for (const file of candidates) {
    try {
      process.loadEnvFile(file);
      return { loaded: true, file };
    } catch (err) {
      if (err?.code !== 'ENOENT') {
        return { loaded: false, file, error: err.message };
      }
    }
  }
  return { loaded: false, reason: 'no_env_file_found' };
}
