const express = require('express');
const router = express.Router();

/**
 * GET /api/admin/stats
 * Получение общей статистики системы
 */
router.get('/stats', (req, res) => {
  try {
    const { deviceManager, sessionManager } = req.app.locals;
    
    const deviceStats = deviceManager.getStats();
    const sessionStats = sessionManager.getStats();
    
    const systemStats = {
      timestamp: new Date().toISOString(),
      uptime: Math.round(process.uptime()),
      memory: process.memoryUsage(),
      devices: deviceStats,
      sessions: sessionStats,
      system: {
        nodeVersion: process.version,
        platform: process.platform,
        arch: process.arch
      }
    };
    
    res.json({
      success: true,
      stats: systemStats
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

/**
 * GET /api/admin/devices
 * Получение списка всех устройств (включая отключенные)
 */
router.get('/devices', (req, res) => {
  try {
    const { deviceManager } = req.app.locals;
    const { status, limit = 100, offset = 0 } = req.query;
    
    let devices = Array.from(deviceManager.devices.values());
    
    // Фильтрация по статусу
    if (status) {
      devices = devices.filter(device => device.status === status);
    }
    
    // Пагинация
    const total = devices.length;
    devices = devices.slice(offset, offset + parseInt(limit));
    
    const devicesData = devices.map(device => device.getSummary());
    
    res.json({
      success: true,
      devices: devicesData,
      pagination: {
        total,
        limit: parseInt(limit),
        offset: parseInt(offset),
        hasMore: (offset + parseInt(limit)) < total
      }
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

/**
 * GET /api/admin/operators
 * Получение списка всех операторов
 */
router.get('/operators', (req, res) => {
  try {
    const { deviceManager } = req.app.locals;
    const { status, limit = 100, offset = 0 } = req.query;
    
    let operators = Array.from(deviceManager.operators.values());
    
    // Фильтрация по статусу
    if (status) {
      operators = operators.filter(operator => operator.status === status);
    }
    
    // Пагинация
    const total = operators.length;
    operators = operators.slice(offset, offset + parseInt(limit));
    
    const operatorsData = operators.map(operator => operator.getSummary());
    
    res.json({
      success: true,
      operators: operatorsData,
      pagination: {
        total,
        limit: parseInt(limit),
        offset: parseInt(offset),
        hasMore: (offset + parseInt(limit)) < total
      }
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

/**
 * GET /api/admin/sessions
 * Получение списка всех сессий
 */
router.get('/sessions', (req, res) => {
  try {
    const { sessionManager } = req.app.locals;
    const { status, deviceId, operatorId, limit = 100, offset = 0 } = req.query;
    
    let sessions = Array.from(sessionManager.sessions.values());
    
    // Фильтрация
    if (status) {
      sessions = sessions.filter(session => session.status === status);
    }
    if (deviceId) {
      sessions = sessions.filter(session => session.deviceId === deviceId);
    }
    if (operatorId) {
      sessions = sessions.filter(session => session.operatorId === operatorId);
    }
    
    // Сортировка по времени создания (новые первыми)
    sessions.sort((a, b) => b.startTime - a.startTime);
    
    // Пагинация
    const total = sessions.length;
    sessions = sessions.slice(offset, offset + parseInt(limit));
    
    const sessionsData = sessions.map(session => session.getSummary());
    
    res.json({
      success: true,
      sessions: sessionsData,
      pagination: {
        total,
        limit: parseInt(limit),
        offset: parseInt(offset),
        hasMore: (offset + parseInt(limit)) < total
      }
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

/**
 * GET /api/admin/sessions/:sessionId
 * Получение детальной информации о сессии (включая события)
 */
router.get('/sessions/:sessionId', (req, res) => {
  try {
    const { sessionId } = req.params;
    const { sessionManager } = req.app.locals;
    
    const session = sessionManager.getSession(sessionId);
    if (!session) {
      return res.status(404).json({ error: 'Session not found' });
    }
    
    res.json({
      success: true,
      session: session.getFullInfo()
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

/**
 * POST /api/admin/sessions/:sessionId/terminate
 * Принудительное завершение сессии
 */
router.post('/sessions/:sessionId/terminate', (req, res) => {
  try {
    const { sessionId } = req.params;
    const { reason = 'Terminated by admin' } = req.body;
    
    const { sessionManager, deviceManager } = req.app.locals;
    const session = sessionManager.getSession(sessionId);
    
    if (!session) {
      return res.status(404).json({ error: 'Session not found' });
    }
    
    const device = deviceManager.getDevice(session.deviceId);
    const operator = deviceManager.getOperator(session.operatorId);
    
    // Уведомляем участников
    if (device && device.isConnected()) {
      device.socket.emit('camera:disconnect', { sessionId, reason });
      device.removeSession(sessionId);
    }
    
    if (operator && operator.isConnected()) {
      operator.socket.emit('camera:disconnected', { sessionId, reason });
      operator.removeSession(sessionId);
    }
    
    // Закрываем сессию
    session.updateStatus('terminated', { reason, terminatedBy: 'admin' });
    sessionManager.closeSession(sessionId);
    
    req.app.locals.logger.warn(`Session ${sessionId} terminated by admin: ${reason}`);
    
    res.json({
      success: true,
      message: 'Session terminated',
      sessionId
    });
    
  } catch (error) {
    req.app.locals.logger.error('Error terminating session', error);
    res.status(500).json({ error: error.message });
  }
});

/**
 * POST /api/admin/devices/:deviceId/disconnect
 * Принудительное отключение устройства
 */
router.post('/devices/:deviceId/disconnect', (req, res) => {
  try {
    const { deviceId } = req.params;
    const { reason = 'Disconnected by admin' } = req.body;
    
    const { deviceManager, sessionManager } = req.app.locals;
    const device = deviceManager.getDevice(deviceId);
    
    if (!device) {
      return res.status(404).json({ error: 'Device not found' });
    }
    
    // Завершаем все активные сессии устройства
    const deviceSessions = sessionManager.getDeviceSessions(deviceId);
    deviceSessions.forEach(session => {
      if (session.status === 'active' || session.status === 'pending') {
        const operator = deviceManager.getOperator(session.operatorId);
        if (operator && operator.isConnected()) {
          operator.socket.emit('camera:disconnected', { 
            sessionId: session.sessionId, 
            reason: `Device disconnected: ${reason}` 
          });
          operator.removeSession(session.sessionId);
        }
        
        session.updateStatus('terminated', { reason, terminatedBy: 'admin' });
        sessionManager.closeSession(session.sessionId);
      }
    });
    
    // Отключаем устройство
    if (device.isConnected()) {
      device.socket.emit('force:disconnect', { reason });
      device.socket.disconnect();
    }
    
    deviceManager.disconnectDevice(deviceId);
    
    req.app.locals.logger.warn(`Device ${deviceId} disconnected by admin: ${reason}`);
    
    res.json({
      success: true,
      message: 'Device disconnected',
      deviceId,
      terminatedSessions: deviceSessions.length
    });
    
  } catch (error) {
    req.app.locals.logger.error('Error disconnecting device', error);
    res.status(500).json({ error: error.message });
  }
});

/**
 * POST /api/admin/cleanup
 * Очистка старых сессий и отключенных устройств
 */
router.post('/cleanup', (req, res) => {
  try {
    const { maxAgeMinutes = 60 } = req.body;
    
    const { deviceManager, sessionManager } = req.app.locals;
    
    // Очистка старых сессий
    const cleanedSessions = sessionManager.cleanupOldSessions(maxAgeMinutes);
    
    // Очистка отключенных устройств
    deviceManager.cleanup();
    
    req.app.locals.logger.info(`Cleanup completed: ${cleanedSessions} sessions removed`);
    
    res.json({
      success: true,
      message: 'Cleanup completed',
      removedSessions: cleanedSessions
    });
    
  } catch (error) {
    req.app.locals.logger.error('Error during cleanup', error);
    res.status(500).json({ error: error.message });
  }
});

/**
 * GET /api/admin/health
 * Проверка состояния системы
 */
router.get('/health', (req, res) => {
  try {
    const { deviceManager, sessionManager } = req.app.locals;
    
    const health = {
      status: 'healthy',
      timestamp: new Date().toISOString(),
      uptime: Math.round(process.uptime()),
      memory: {
        used: Math.round(process.memoryUsage().heapUsed / 1024 / 1024),
        total: Math.round(process.memoryUsage().heapTotal / 1024 / 1024),
        external: Math.round(process.memoryUsage().external / 1024 / 1024)
      },
      connections: {
        devices: deviceManager.getConnectedDevices().length,
        operators: deviceManager.getConnectedOperators().length,
        activeSessions: sessionManager.getActiveSessions().length
      }
    };
    
    // Проверка на критические состояния
    if (health.memory.used / health.memory.total > 0.9) {
      health.status = 'warning';
      health.warnings = health.warnings || [];
      health.warnings.push('High memory usage');
    }
    
    if (health.uptime < 60) {
      health.status = 'warning';
      health.warnings = health.warnings || [];
      health.warnings.push('Recently restarted');
    }
    
    res.json({
      success: true,
      health
    });
    
  } catch (error) {
    res.status(500).json({ 
      success: false,
      health: {
        status: 'unhealthy',
        error: error.message,
        timestamp: new Date().toISOString()
      }
    });
  }
});

/**
 * GET /api/admin/logs
 * Получение логов системы (последние записи)
 */
router.get('/logs', (req, res) => {
  try {
    const fs = require('fs');
    const path = require('path');
    const { lines = 100 } = req.query;
    
    const logFile = path.join(process.cwd(), 'god-eye.log');
    
    if (!fs.existsSync(logFile)) {
      return res.json({
        success: true,
        logs: [],
        message: 'Log file not found'
      });
    }
    
    const logData = fs.readFileSync(logFile, 'utf8');
    const logLines = logData.trim().split('\n').slice(-parseInt(lines));
    
    const logs = logLines.map(line => {
      try {
        return JSON.parse(line);
      } catch (e) {
        return { message: line, timestamp: new Date().toISOString(), level: 'info' };
      }
    }).reverse(); // Новые записи сверху
    
    res.json({
      success: true,
      logs,
      total: logs.length
    });
    
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;