import type { FastifyInstance } from 'fastify';
import { z } from 'zod';
import { getActiveChatService } from '../services/chat-service.js';
import {
  beginRuntimeDrain,
  endRuntimeDrain,
  getRuntimeDrainSnapshot,
} from '../services/runtime-drain-service.js';

const runtimeDrainBodySchema = z.object({
  draining: z.boolean(),
});

function buildRuntimeResponse() {
  const chatRuntimeSnapshot = getActiveChatService()?.getRuntimeSnapshot() ?? null;

  return {
    ok: true,
    ...getRuntimeDrainSnapshot(),
    activeChatRequestCount: chatRuntimeSnapshot?.activeRequestCount ?? 0,
    queuedChatRequestCount: chatRuntimeSnapshot?.queuedRequestCount ?? 0,
    connectedChatSessionCount: chatRuntimeSnapshot?.connectedSessionCount ?? 0,
    activeChatSocketCount: chatRuntimeSnapshot?.activeSocketCount ?? 0,
    canAcceptNewChatRequests: chatRuntimeSnapshot?.canAcceptNewRequests ?? true,
  };
}

export async function registerRuntimeRoutes(app: FastifyInstance) {
  app.get('/api/runtime', async () => buildRuntimeResponse());

  app.post('/api/runtime/recover-interrupted-chat', async () => {
    const recovered = await getActiveChatService()?.recoverInterruptedSessions();

    return {
      ok: true,
      recovered: recovered ?? {
        sessionCount: 0,
        restartedCount: 0,
        requeuedCount: 0,
      },
    };
  });

  app.post('/api/runtime/drain', async (request) => {
    const { draining } = runtimeDrainBodySchema.parse(request.body ?? {});

    if (draining) {
      beginRuntimeDrain();
    } else {
      endRuntimeDrain();
    }

    return buildRuntimeResponse();
  });
}
