import { config } from 'dotenv';
import { existsSync } from 'fs';
import { hostname } from 'os';
import { resolve } from 'path';

const getEnvPath = () => {
  if (process.env.DOTENV_CONFIG_PATH) return process.env.DOTENV_CONFIG_PATH;
  
  const localEnv = resolve(process.cwd(), '.env');
  if (existsSync(localEnv)) return localEnv;

  const rootEnv = resolve(process.cwd(), '../../.env');
  if (existsSync(rootEnv)) return rootEnv;

  return localEnv;
};

config({ path: getEnvPath() });

const generateInstanceId = () => {
  return process.env.INSTANCE_ID || hostname() || `kord-${Math.random().toString(36).substring(2, 7)}`;
};

export const env = {
  NODE_ENV: process.env.NODE_ENV || 'development',
  DISCORD_TOKEN: process.env.DISCORD_TOKEN || '',
  DISCORD_CLIENT_ID: process.env.DISCORD_CLIENT_ID || '',
  DATABASE_URL: process.env.DATABASE_URL || '',
  VOICE_WAITING_ROOM_ID: process.env.VOICE_WAITING_ROOM_ID || '',
  VOICE_CATEGORY_ID: process.env.VOICE_CATEGORY_ID || '',
  /** log4js level: trace | debug | info | warn | error | fatal */
  LOG_LEVEL: process.env.LOG_LEVEL || 'info',
  /**
   * Directory for log4js `kord.log` (created at startup). Relative paths resolve from `process.cwd()`.
   * For Jenkins or wipe-and-redeploy flows, set an absolute path **outside** the deploy tree (e.g. `/var/lib/kord/logs`)
   * so logs survive redeploys and match `StandardOutput=append` in systemd if you point it at the same file.
   */
  LOG_DIR: process.env.LOG_DIR || 'logs',
  INSTANCE_ID: generateInstanceId(),
};
