import { readFileSync, existsSync } from "node:fs"

const parseEnvLine = (line: string) => {
    const trimmed = line.trim()
    if (!trimmed || trimmed.startsWith("#")) return null

    const separator = trimmed.indexOf("=")
    if (separator === -1) return null

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

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

    return { key, value }
}

export const loadDotEnv = (path = ".env") => {
    if (!existsSync(path)) return

    const content = readFileSync(path, "utf8")
    for (const line of content.split(/\r?\n/)) {
        const parsed = parseEnvLine(line)
        if (!parsed) continue
        if (process.env[parsed.key] === undefined) process.env[parsed.key] = parsed.value
    }
}
