import { Hono } from 'hono';
import { IServiceContainer } from '@stock-bot/di';
import { createOrderRoutes } from '../api/rest/orders';
import { createPositionRoutes } from '../api/rest/positions';
import { createAnalyticsRoutes } from '../api/rest/analytics';
import { createBacktestRoutes } from '../api/rest/backtest';
import { setupWebSocketHandlers } from '../api/websocket';
import { Server as SocketIOServer } from 'socket.io';

/**
 * Create all routes for the orchestrator service
 */
export function createRoutes(
  services: IServiceContainer,
  io?: SocketIOServer
): Hono {
  const app = new Hono();
  services.logger.info('Creating orchestrator routes');

  // Health check with mode status
  app.get('/health', (c) => {
    const modeManager = services.custom?.ModeManager;
    return c.json({
      status: 'healthy',
      service: 'orchestrator',
      mode: modeManager?.getCurrentMode() || 'unknown',
      timestamp: new Date().toISOString()
    });
  });

  // Mount REST API routes
  app.route('/api/orders', createOrderRoutes(services));
  app.route('/api/positions', createPositionRoutes(services));
  app.route('/api/analytics', createAnalyticsRoutes(services));
  app.route('/api/backtest', createBacktestRoutes(services));

  // Setup WebSocket handlers if Socket.IO is provided
  if (io) {
    setupWebSocketHandlers(io, services);
    services.logger.info('WebSocket handlers configured');
  }

  // Add request logging middleware
  app.use('*', async (c, next) => {
    const start = Date.now();
    await next();
    const ms = Date.now() - start;
    services.logger.debug(`${c.req.method} ${c.req.url} - ${ms}ms`);
  });

  return app;
}