import Fastify from 'fastify';
import cors from '@fastify/cors';
import websocket from '@fastify/websocket';
import { getDb, saveDb } from './db/database';
import { authRoutes } from './routes/auth.routes';
import { deviceRoutes } from './routes/device.routes';
import { nodeRoutes } from './routes/node.routes';
import { connectionRoutes } from './routes/connection.routes';

const PORT = parseInt(process.env.PORT || '3001', 10);
const HOST = process.env.HOST || '0.0.0.0';

async function main() {
  // 异步初始化数据库
  await getDb();
  console.log('[Server] 数据库已初始化');

  const app = Fastify({
    logger: {
      level: 'info',
      transport: {
        target: 'pino-pretty',
        options: { colorize: true },
      },
    },
  });

  // 插件
  await app.register(cors, { origin: true });
  await app.register(websocket);

  // WebSocket 端点
  const connectedClients = new Set<any>();

  app.get('/ws', { websocket: true }, (socket, _req) => {
    connectedClients.add(socket);
    console.log(`[WS] 客户端连接，当前连接数: ${connectedClients.size}`);

    socket.on('message', (data: Buffer) => {
      try {
        const msg = JSON.parse(data.toString());
        for (const client of connectedClients) {
          if (client !== socket && client.readyState === 1) {
            client.send(JSON.stringify(msg));
          }
        }
      } catch { /* ignore */ }
    });

    socket.on('close', () => {
      connectedClients.delete(socket);
      console.log(`[WS] 客户端断开，当前连接数: ${connectedClients.size}`);
    });
  });

  // 注册路由
  await app.register(authRoutes);
  await app.register(deviceRoutes);
  await app.register(nodeRoutes);
  await app.register(connectionRoutes);

  // 健康检查
  app.get('/api/health', async () => ({
    success: true,
    message: 'Control Server is running',
    timestamp: new Date().toISOString(),
  }));

  // 全局错误处理
  app.setErrorHandler((error, _request, reply) => {
    console.error('[Server Error]', error);
    reply.status(error.statusCode || 500).send({
      success: false,
      error: 'INTERNAL_ERROR',
      message: error.message || 'Internal server error',
    });
  });

  // 定时保存数据库（sql.js 是内存型，需要定期持久化）
  setInterval(() => {
    try {
      saveDb();
    } catch { /* ignore */ }
  }, 30000);

  // 定时清理过期数据
  setInterval(async () => {
    try {
      const db = await getDb();
      const { execute } = require('./db/database');
      execute(db, "UPDATE relay_nodes SET status = 'offline' WHERE status != 'offline' AND last_heartbeat_at < datetime('now', '-5 minutes')");
      execute(db, "DELETE FROM connection_tokens WHERE expires_at < datetime('now') AND used_at IS NULL");
      saveDb();
    } catch { /* ignore */ }
  }, 60000);

  // 启动服务
  await app.listen({ port: PORT, host: HOST });
  console.log(`[Server] Control Server 已启动: http://${HOST}:${PORT}`);
  console.log(`[Server] WebSocket: ws://${HOST}:${PORT}/ws`);
}

main().catch((err) => {
  console.error('[Server] 启动失败:', err);
  process.exit(1);
});
