"use strict";

import environment from "@/lib/environment.ts";
import config from "@/lib/config.ts";
import "@/lib/initialize.ts";
import server from "@/lib/server.ts";
import routes from "@/api/routes/index.ts";
import logger from "@/lib/logger.ts";
import nedbManager from "@/lib/database/nedb.ts";
import nedbCleanupService from "@/lib/services/NeDBCleanupService.ts";

import taskPollingService from "@/lib/services/TaskPollingService.js";

const startupTime = performance.now();

(async () => {
  logger.header();

  logger.info("<<<< jimeng free server >>>>");
  logger.info("Version:", environment.package.version);
  logger.info("Process id:", process.pid);
  logger.info("Environment:", environment.env);
  logger.info("Service name:", config.service.name);
  logger.info("Service host:", config.service.host);
  logger.info("Service port:", config.service.port);

  // 初始化 NeDB 数据库
  try {
    await nedbManager.initialize();
    logger.success("NeDB database initialized");
    
    // 启动数据清理服务
    await nedbCleanupService.start();
    logger.success("NeDB cleanup service started");
  } catch (error) {
    logger.warn("NeDB initialization failed, continuing without database:", error.message);
  }

  server.attachRoutes(routes);
  await server.listen();

  // 心跳服务已移除，使用 NeDB 本地存储

  // 启动任务轮询服务（仅在数据库模式下）
  const useDatabaseMode = process.env.USE_DATABASE_MODE === 'true';
  if (useDatabaseMode) {
    try {
      await taskPollingService.start();
      logger.success("Task polling service started");
    } catch (error) {
      logger.warn("Failed to start task polling service:", error.message);
    }
  }

  config.service.bindAddress &&
    logger.success("Service bind address:", config.service.bindAddress);
})()
  .then(() =>
    logger.success(
      `Service startup completed (${Math.floor(performance.now() - startupTime)}ms)`
    )
  )
  .catch((err) => console.error(err));
