#!/usr/bin/env node
/**
 * Startup environment validation (§59). Fails fast with an actionable message rather
 * than letting the app boot into a half-configured state.
 */
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'

const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')

function loadEnvFiles() {
  const merged = {}
  for (const file of ['.env', '.env.local']) {
    let raw = ''
    try {
      raw = readFileSync(join(ROOT, file), 'utf8')
    } catch {
      continue
    }
    for (const line of raw.split(/\r?\n/)) {
      const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)$/)
      if (m) merged[m[1]] = m[2].trim().replace(/^["']|["']$/g, '')
    }
  }
  return { ...merged, ...process.env }
}

const env = loadEnvFiles()
const errors = []
const warnings = []

const required = ['DATABASE_PROVIDER', 'DATABASE_URL', 'AUTH_SECRET']
for (const key of required) {
  if (!env[key]) errors.push(`Missing required variable: ${key}`)
}

if (env.DATABASE_PROVIDER && !['sqlite', 'postgresql'].includes(env.DATABASE_PROVIDER)) {
  errors.push(`DATABASE_PROVIDER must be "sqlite" or "postgresql" (got "${env.DATABASE_PROVIDER}")`)
}

if (env.DATABASE_PROVIDER === 'postgresql' && env.DATABASE_URL && !/^postgres(ql)?:\/\//.test(env.DATABASE_URL)) {
  errors.push('DATABASE_PROVIDER is "postgresql" but DATABASE_URL is not a postgres:// URL')
}

if (env.DATABASE_PROVIDER === 'sqlite' && env.DATABASE_URL && !env.DATABASE_URL.startsWith('file:')) {
  errors.push('DATABASE_PROVIDER is "sqlite" but DATABASE_URL is not a file: URL')
}

if (env.AUTH_SECRET && env.AUTH_SECRET.length < 32) {
  errors.push('AUTH_SECRET must be at least 32 characters')
}

if (env.NODE_ENV === 'production') {
  if (env.AUTH_SECRET === 'nabdh-development-secret-change-me-please-0001') {
    errors.push('AUTH_SECRET is still the development placeholder — set a real secret in production')
  }
  if (env.DEMO_ACCOUNTS_ENABLED === 'true') {
    warnings.push('DEMO_ACCOUNTS_ENABLED=true in production — seeded demo credentials would be usable')
  }
}

for (const w of warnings) console.warn(`[env]  warning: ${w}`)

if (errors.length) {
  console.error('\n[env]  Environment validation failed:\n')
  for (const e of errors) console.error(`   - ${e}`)
  console.error('\n   Copy .env.example to .env and fill in the values.\n')
  process.exit(1)
}

console.log(`[env]  ok — provider=${env.DATABASE_PROVIDER}, node=${process.version}`)
