import fs from 'fs';
import path from 'path';

const __dirname = import.meta.dirname;
// Path: shared/config -> shared -> src -> backend/.env (3 levels up)
const ENV_FILE = path.resolve(__dirname, '..', '..', '..', '.env');

interface EnvEntry {
  key: string;
  value: string;
}

function parseEnvLine(line: string): EnvEntry | null {
  const trimmed = line.trim();

  if (!trimmed || trimmed.startsWith('#')) {
    return null;
  }

  const separatorIndex = trimmed.indexOf('=');

  if (separatorIndex === -1) {
    return null;
  }

  const key = trimmed.slice(0, separatorIndex).trim();
  let value = trimmed.slice(separatorIndex + 1).trim();

  if (!key) {
    return null;
  }

  if (
    (value.startsWith('"') && value.endsWith('"')) ||
    (value.startsWith("'") && value.endsWith("'"))
  ) {
    value = value.slice(1, -1);
  }

  return { key, value };
}

function loadEnvFile(): void {
  if (!fs.existsSync(ENV_FILE)) {
    return;
  }

  const file = fs.readFileSync(ENV_FILE, 'utf8');

  for (const line of file.split(/\r?\n/)) {
    const entry = parseEnvLine(line);

    if (entry && process.env[entry.key] === undefined) {
      process.env[entry.key] = entry.value;
    }
  }
}

loadEnvFile();
