import type { FastifyInstance } from 'fastify';
import { getActiveChatService } from '../services/chat-service.js';
import { getRuntimeDrainSnapshot } from '../services/runtime-drain-service.js';
import { getRuntimeWorkServerBuildInfo } from '../services/work-server-build-service.js';

export async function registerHealthRoutes(app: FastifyInstance) {
  const respondHealth = async () => {
    const buildInfo = getRuntimeWorkServerBuildInfo();
    const chatRuntimeSnapshot = getActiveChatService()?.getRuntimeSnapshot() ?? null;

    return {
      ok: true,
      service: 'work-server',
      slot: process.env.WORK_SERVER_SLOT?.trim() || null,
      timestamp: new Date().toISOString(),
      buildId: buildInfo?.buildId ?? null,
      builtAt: buildInfo?.builtAt ?? null,
      ...getRuntimeDrainSnapshot(),
      activeChatRequestCount: chatRuntimeSnapshot?.activeRequestCount ?? 0,
      queuedChatRequestCount: chatRuntimeSnapshot?.queuedRequestCount ?? 0,
      connectedChatSessionCount: chatRuntimeSnapshot?.connectedSessionCount ?? 0,
      activeChatSocketCount: chatRuntimeSnapshot?.activeSocketCount ?? 0,
      canAcceptNewChatRequests: chatRuntimeSnapshot?.canAcceptNewRequests ?? true,
    };
  };

  app.get('/', respondHealth);
  app.get('/api', respondHealth);
  app.get('/health', respondHealth);
}
