import express from 'express'
import cookieParser from 'cookie-parser'
import session from 'express-session'
import morgan from 'morgan'
import path from 'path'
import 'dotenv/config'

import root from './server'
import { errorHandler } from './error'
import kfuM241Router from './routers/kfu-m-24-1'
import epja20241Router from './routers/epja-2024-1'
import todoRouter from './routers/todo'
import dogsittersFinderRouter from './routers/dogsitters-finder'
import kazanExploreRouter from './routers/kazan-explore'
import edateamRouter from './routers/edateam-legacy'
import dryWashRouter from './routers/dry-wash'
import freetrackerRouter from './routers/freetracker'
import dhsTestingRouter from './routers/dhs-testing'
import gamehubRouter from './routers/gamehub'
import escRouter from './routers/esc'
import connectmeRouter from './routers/connectme'
import questioneerRouter from './routers/questioneer'
import { setIo } from './io'
const { createChatPollingRouter } = require('./routers/kfu-m-24-1/sber_mobile/polling-chat')

export const app = express()

// Динамический импорт rotating-file-stream
const initServer = async () => {
  const rfs = await import('rotating-file-stream')
  const accessLogStream = rfs.createStream("access.log", {
    size: "10M",
    interval: "1d",
    compress: "gzip",
    path: path.join(__dirname, "log"),
  })
  
  const errorLogStream = rfs.createStream("error.log", {
    size: "10M",
    interval: "1d",
    compress: "gzip",
    path: path.join(__dirname, "log"),
  })

  app.use(cookieParser())
  app.use(
    morgan("combined", {
      stream: accessLogStream,
      skip: function (req, res) {
        return res.statusCode >= 400
      },
    })
  )

  // log all requests to access.log
  app.use(
    morgan("combined", {
      stream: errorLogStream,
      skip: function (req, res) {
        console.log('statusCode', res.statusCode, res.statusCode <= 400)
        return res.statusCode < 400
      },
    })
  )

  console.log('warming up 🔥')

  const sess = {
    secret: "super-secret-key",
    resave: true,
    saveUninitialized: true,
    cookie: {},
  }
  if (app.get("env") !== "development") {
    app.set("trust proxy", 1)
  }
  app.use(session(sess))

  app.use(
    express.json({
      limit: "50mb",
    })
  )
  app.use(
    express.urlencoded({
      limit: "50mb",
      extended: true,
    })
  )
  app.use(root)

  // Инициализация Polling для чата (после настройки middleware)
  const { router: chatPollingRouter, chatHandler } = createChatPollingRouter(express)


  /**
   * Добавляйте сюда свои routers.
   */
  app.use("/kfu-m-24-1", kfuM241Router)
  
  // Добавляем Polling роутер для чата
  app.use("/kfu-m-24-1/sber_mobile", chatPollingRouter)
  
  app.use("/epja-2024-1", epja20241Router)
  app.use("/v1/todo", todoRouter)
  app.use("/dogsitters-finder", dogsittersFinderRouter)
  app.use("/kazan-explore", kazanExploreRouter)
  app.use("/edateam", edateamRouter)
  app.use("/dry-wash", dryWashRouter)
  app.use("/freetracker", freetrackerRouter)
  app.use("/dhs-testing", dhsTestingRouter)
  app.use("/gamehub", gamehubRouter) 
  app.use("/esc", escRouter)
  app.use('/connectme', connectmeRouter)
  app.use('/questioneer', questioneerRouter)

  app.use(errorHandler)

  // Создаем обычный HTTP сервер
  const server = app.listen(process.env.PORT ?? 8044, () => {
    console.log(`🚀 Сервер запущен на http://localhost:${process.env.PORT ?? 8044}`)
  })

  // Обработка сигналов завершения процесса
  process.on('SIGTERM', () => {
    console.log('🛑 Получен сигнал SIGTERM. Выполняется корректное завершение...')
    server.close(() => {
      console.log('✅ Сервер успешно остановлен')
      process.exit(0)
    })
  })

  process.on('SIGINT', () => {
    console.log('🛑 Получен сигнал SIGINT. Выполняется корректное завершение...')
    server.close(() => {
      console.log('✅ Сервер успешно остановлен')
      process.exit(0)
    })
  })

  // Обработка необработанных исключений
  process.on('uncaughtException', (err) => {
    console.error('❌ Необработанное исключение:', err)
    server.close(() => {
      process.exit(1)
    })
  })

  // Обработка необработанных отклонений промисов
  process.on('unhandledRejection', (reason, promise) => {
    console.error('⚠️ Необработанное отклонение промиса:', reason)
    server.close(() => {
      process.exit(1)
    })
  })

  return server
}

initServer().catch(console.error)
