import type { GatewayRequest, OutboundMessage } from '../protocol.js';
import { makeError, makeResponse, ErrorCode } from '../protocol.js';
import type { ComponentRegistry } from '../../intents/index.js';
import type { RoutingPolicy } from '../../routing/index.js';

export interface RoutingHandlerDeps {
  intentRegistry?: ComponentRegistry;
  routingPolicy?: RoutingPolicy;
}

export function createRoutingHandlers(deps: RoutingHandlerDeps) {
  return {
    'routing.decide': async (request: GatewayRequest): Promise<OutboundMessage> => {
      const params = request.params as { input?: string } | undefined;
      if (!params?.input) {
        return makeError(request.id, ErrorCode.InvalidRequest, 'input is required');
      }

      const match = deps.intentRegistry?.match(params.input) ?? null;
      const decision = deps.routingPolicy?.decide({ confidence: match?.score ?? null }) ?? {
        path: 'llm',
        reason: 'disabled',
      };

      return makeResponse(request.id, {
        match,
        decision,
      });
    },
  };
}
