import { Hono } from 'hono';
import { z } from 'zod';
import { IServiceContainer } from '@stock-bot/di';
import { ModeManager } from '../../core/ModeManager';

const SymbolSchema = z.object({
  symbol: z.string()
});

export function createPositionRoutes(container: IServiceContainer): Hono {
  const app = new Hono();
  const modeManager = container.custom?.ModeManager as ModeManager;

  // Get all positions
  app.get('/', async (c) => {
    try {
      const tradingEngine = modeManager.getTradingEngine();
      const positions = JSON.parse(tradingEngine.getAllPositions());
      
      return c.json({
        mode: modeManager.getCurrentMode(),
        positions
      });
    } catch (error) {
      container.logger.error('Error getting positions:', error);
      return c.json({ 
        error: error instanceof Error ? error.message : 'Failed to get positions' 
      }, 500);
    }
  });

  // Get open positions only
  app.get('/open', async (c) => {
    try {
      const tradingEngine = modeManager.getTradingEngine();
      const positions = JSON.parse(tradingEngine.getOpenPositions());
      
      return c.json({
        mode: modeManager.getCurrentMode(),
        positions
      });
    } catch (error) {
      container.logger.error('Error getting open positions:', error);
      return c.json({ 
        error: error instanceof Error ? error.message : 'Failed to get open positions' 
      }, 500);
    }
  });

  // Get position for specific symbol
  app.get('/:symbol', async (c) => {
    try {
      const { symbol } = SymbolSchema.parse(c.req.param());
      const tradingEngine = modeManager.getTradingEngine();
      
      const positionJson = tradingEngine.getPosition(symbol);
      const position = positionJson ? JSON.parse(positionJson) : null;
      
      if (position) {
        return c.json({
          mode: modeManager.getCurrentMode(),
          position
        });
      } else {
        return c.json({ 
          error: 'Position not found',
          symbol 
        }, 404);
      }
    } catch (error) {
      container.logger.error('Error getting position:', error);
      return c.json({ 
        error: error instanceof Error ? error.message : 'Failed to get position' 
      }, 500);
    }
  });

  // Get P&L summary
  app.get('/pnl/summary', async (c) => {
    try {
      const tradingEngine = modeManager.getTradingEngine();
      const [realizedPnl, unrealizedPnl] = tradingEngine.getTotalPnl();
      
      return c.json({
        mode: modeManager.getCurrentMode(),
        pnl: {
          realized: realizedPnl,
          unrealized: unrealizedPnl,
          total: realizedPnl + unrealizedPnl
        },
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      container.logger.error('Error getting P&L:', error);
      return c.json({ 
        error: error instanceof Error ? error.message : 'Failed to get P&L' 
      }, 500);
    }
  });

  // Get risk metrics
  app.get('/risk/metrics', async (c) => {
    try {
      const tradingEngine = modeManager.getTradingEngine();
      const metrics = JSON.parse(tradingEngine.getRiskMetrics());
      
      return c.json({
        mode: modeManager.getCurrentMode(),
        risk: metrics,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      container.logger.error('Error getting risk metrics:', error);
      return c.json({ 
        error: error instanceof Error ? error.message : 'Failed to get risk metrics' 
      }, 500);
    }
  });

  return app;
}