import { NestFactory } from '@nestjs/core';
import { Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestExpressApplication } from '@nestjs/platform-express';
import { WsAdapter } from '@nestjs/platform-ws';
import { AgentModule } from './agent.module';

const logger = new Logger('AgentService');

// Prevent process crash from unhandled errors
process.on('unhandledRejection', (reason) => {
  logger.error(`Unhandled Rejection: ${reason}`);
});
process.on('uncaughtException', (error) => {
  logger.error(`Uncaught Exception: ${error.message}`, error.stack);
});

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AgentModule);
  // Claude API: max 32MB PDF + 5MB images; base64 adds ~33% overhead → 50mb covers all cases
  app.useBodyParser('json', { limit: '50mb' });
  // Use raw WebSocket adapter instead of Socket.IO
  app.useWebSocketAdapter(new WsAdapter(app));
  const config = app.get(ConfigService);
  const port = config.get<number>('AGENT_SERVICE_PORT', 3002);
  await app.listen(port);
  logger.log(`agent-service running on port ${port}`);
}
bootstrap().catch((err) => {
  logger.error(`Failed to start agent-service: ${err.message}`, err.stack);
  process.exit(1);
});
