import { existsSync, readFileSync } from 'fs'
import { join } from 'path'

export function loadAppEnv(appName: string, toesDir?: string): Record<string, string> {
  const envDir = join(toesDir || process.env.TOES_DIR!, 'env')
  const env: Record<string, string> = {}

  const parseEnvFile = (path: string) => {
    if (!existsSync(path)) return
    const content = readFileSync(path, 'utf-8')
    for (const line of content.split('\n')) {
      const trimmed = line.trim()
      if (!trimmed || trimmed.startsWith('#')) continue
      const eqIndex = trimmed.indexOf('=')
      if (eqIndex === -1) continue
      const key = trimmed.slice(0, eqIndex).trim()
      let value = trimmed.slice(eqIndex + 1).trim()
      if ((value.startsWith('"') && value.endsWith('"')) ||
          (value.startsWith("'") && value.endsWith("'"))) {
        value = value.slice(1, -1)
      }
      if (key) env[key] = value
    }
  }

  parseEnvFile(join(envDir, '_global.env'))
  parseEnvFile(join(envDir, `${appName}.env`))

  return env
}
