require('dotenv').config()

const app = require('./app')
const bootstrap = require('./bootstrap')
const createLogger = require('./utils/logger')
const discordManager = require('./discord/discordManager')
const brand = require('./brand')
const pkg = require('../package.json')

const log = createLogger('server')
const PORT = Number(process.env.PORT) || 4100
const HOST = '0.0.0.0'

async function start() {
  log.info(`starting ${brand.name} bot v${pkg.version}`, {
    node: process.version,
    logFile: createLogger.logFilePath || 'disabled (console only)',
  })

  const server = app.listen(PORT, HOST, () => {
    log.info(`internal API listening on http://${HOST}:${PORT}`)
  })

  // Pick up the site's effective accent before the first embed can be built.
  // Best-effort by design: it never rejects, and a site that is not up yet just
  // leaves the bot on its BRAND_ACCENT_COLOR default until the next read.
  await brand.refreshAccent()

  await bootstrap()

  setupShutdown(server)
}

function setupShutdown(server) {
  let closing = false
  const shutdown = async (signal) => {
    if (closing) return
    closing = true
    log.warn(`${signal} received — shutting down gracefully`)
    server.close(() => log.info('internal API closed'))
    await discordManager.stop()
    await createLogger.close()
    process.exit(0)
  }

  process.on('SIGINT', () => shutdown('SIGINT'))
  process.on('SIGTERM', () => shutdown('SIGTERM'))
  process.on('unhandledRejection', (reason) => log.error('unhandledRejection', { reason: String(reason) }))
  process.on('uncaughtException', (err) => {
    log.error('uncaughtException', err)
    process.exit(1)
  })
}

start().catch((err) => {
  log.error('failed to start bot', err)
  process.exit(1)
})
