import fs from 'node:fs'
import path from 'node:path'

function parseEnvLine(line) {
    const trimmed = line.trim()
    if (!trimmed || trimmed.startsWith('#')) return null
    const idx = trimmed.indexOf('=')
    if (idx <= 0) return null
    const key = trimmed.slice(0, idx).trim()
    let value = trimmed.slice(idx + 1).trim()
    if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
        value = value.slice(1, -1)
    }
    return [key, value]
}

function loadLocalEnvFiles() {
    const cwd = process.cwd()
    const nodeEnv = process.env.NODE_ENV || 'development'
    const files = [
        `.env.${nodeEnv}.local`,
        '.env.local',
        `.env.${nodeEnv}`,
        '.env',
    ]

    for (const fileName of files) {
        const fullPath = path.join(cwd, fileName)
        if (!fs.existsSync(fullPath)) continue

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

loadLocalEnvFiles()

const useMockApi = process.env.NEXT_PUBLIC_USE_MOCK_API === 'true'
const baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL

if (!useMockApi && !baseUrl) {
    console.error('NEXT_PUBLIC_API_BASE_URL is required when NEXT_PUBLIC_USE_MOCK_API is false.')
    process.exit(1)
}

if (baseUrl && !/^https?:\/\//.test(baseUrl)) {
    console.error('NEXT_PUBLIC_API_BASE_URL must start with http:// or https://')
    process.exit(1)
}
