import fs from 'fs'
import { initializeDatabase, closeDatabaseConnection } from '../lib/db'

function loadEnv(): void {
  const envPath = process.env.ENV_PATH ?? '/opt/peercortex-app/.env'
  try {
    const envContent = fs.readFileSync(envPath, 'utf8')
    for (const line of envContent.split('\n')) {
      const trimmed = line.trim()
      if (!trimmed || trimmed.startsWith('#')) continue
      const eqIdx = trimmed.indexOf('=')
      if (eqIdx > 0) {
        const key = trimmed.substring(0, eqIdx).trim()
        const val = trimmed.substring(eqIdx + 1).trim()
        if (!process.env[key]) process.env[key] = val
      }
    }
    console.log('[API] Environment variables loaded from', envPath)
  } catch {
    console.warn('[API] Could not read .env file at', envPath)
  }
}

async function main(): Promise<void> {
  loadEnv()

  // initializeDatabase() must run before anything imports src/routes/hijack-alerts,
  // which calls getDatabase() at module load time. Dynamic import defers evaluation
  // of ./server (and its own static imports) until after the pool exists.
  initializeDatabase()

  const { startApiServer } = await import('./server.js')
  const port = parseInt(process.env.API_PORT ?? '3102', 10)
  await startApiServer(port)
}

async function shutdown(signal: string): Promise<void> {
  console.log(`[API] ${signal} received, shutting down`)
  await closeDatabaseConnection()
  process.exit(0)
}

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

main().catch((error) => {
  console.error('[API] Fatal startup error:', error)
  process.exit(1)
})
