const fs = require('fs')
const path = require('path')

/**
 * Loads environment variables from local files without requiring extra dependencies.
 * Priority: .env, then .env.example for any keys that are still unset.
 *
 * @returns {void}
 */
function loadEnvironmentFiles() {
  const candidateFiles = ['.env', '.env.example']

  for (const fileName of candidateFiles) {
    const filePath = path.resolve(process.cwd(), fileName)
    if (!fs.existsSync(filePath)) {
      continue
    }

    const lines = fs.readFileSync(filePath, 'utf8').split(/\r?\n/)
    for (const rawLine of lines) {
      const line = rawLine.trim()
      if (!line || line.startsWith('#')) {
        continue
      }

      const separatorIndex = line.indexOf('=')
      if (separatorIndex === -1) {
        continue
      }

      const key = line.slice(0, separatorIndex).trim()
      const value = line.slice(separatorIndex + 1).trim().replace(/^['"]|['"]$/g, '')
      if (!(key in process.env)) {
        process.env[key] = value
      }
    }
  }
}

module.exports = {
  loadEnvironmentFiles
}