import { spawn } from 'node:child_process'
import fs from 'node:fs'

const loadLocalEnv = () => {
  if (!fs.existsSync('.env.local')) return {}
  return Object.fromEntries(
    fs.readFileSync('.env.local', 'utf8')
      .split(/\r?\n/)
      .map((line) => line.trim())
      .filter((line) => line && !line.startsWith('#') && line.includes('='))
      .map((line) => {
        const index = line.indexOf('=')
        return [line.slice(0, index), line.slice(index + 1).replace(/^["']|["']$/g, '')]
      }),
  )
}

const env = { ...process.env, ...loadLocalEnv() }

const processes = [
  spawn(process.execPath, ['server/server.js'], {
    stdio: 'inherit',
    env: { ...env, PORT: env.PORT || '3001', DEV_SEED_MEMBERS: env.DEV_SEED_MEMBERS || 'true' },
  }),
  spawn(process.execPath, ['node_modules/vite/bin/vite.js', '--host'], {
    stdio: 'inherit',
    env,
  }),
]

let isShuttingDown = false

const shutdown = (code = 0) => {
  if (isShuttingDown) return
  isShuttingDown = true
  for (const child of processes) {
    if (!child.killed) child.kill('SIGTERM')
  }
  process.exit(code)
}

for (const child of processes) {
  child.on('exit', (code) => {
    if (!isShuttingDown && code !== 0) shutdown(code || 1)
  })
}

process.on('SIGINT', () => shutdown(0))
process.on('SIGTERM', () => shutdown(0))
