import fs from 'node:fs'
import process from 'node:process'

export function loadEnvFiles(filePaths: string[]): void {
  for (const filePath of filePaths) {
    loadEnvFile(filePath)
  }
}

function loadEnvFile(filePath: string): void {
  if (!fs.existsSync(filePath)) {
    return
  }

  const rawText = fs.readFileSync(filePath, 'utf8')
  const lines = rawText.split(/\r?\n/)

  for (const rawLine of lines) {
    const line = rawLine.trim()

    if (!line || line.startsWith('#')) {
      continue
    }

    const separatorIndex = line.indexOf('=')
    if (separatorIndex <= 0) {
      continue
    }

    const key = line.slice(0, separatorIndex).trim()
    if (!key || key in process.env) {
      continue
    }

    process.env[key] = parseEnvValue(line.slice(separatorIndex + 1))
  }
}

function parseEnvValue(rawValue: string): string {
  const value = String(rawValue || '').trim()

  if (!value) {
    return ''
  }

  const quote = value[0]
  if ((quote === '"' || quote === "'") && value.endsWith(quote)) {
    return value.slice(1, -1)
  }

  return value
}

export function parseBoolean(rawValue: unknown): boolean | null {
  const normalized = String(rawValue || '')
    .trim()
    .toLowerCase()

  if (!normalized) {
    return null
  }

  if (['1', 'true', 'yes', 'on'].includes(normalized)) {
    return true
  }

  if (['0', 'false', 'no', 'off'].includes(normalized)) {
    return false
  }

  return null
}

export function parseInteger(rawValue: unknown): number | null {
  const normalized = String(rawValue || '').trim()

  if (!normalized) {
    return null
  }

  const parsed = Number(normalized)
  return Number.isFinite(parsed) ? parsed : null
}

export function parseJsonArray<T = unknown>(rawValue: unknown): T[] | null {
  const normalized = String(rawValue || '').trim()

  if (!normalized) {
    return null
  }

  try {
    const parsed = JSON.parse(normalized)
    return Array.isArray(parsed) ? (parsed as T[]) : null
  } catch {
    return null
  }
}
