import { MonitoringConfig, MonitoringStatus, Alert, AlertStatus } from '../types/monitoring';
import { logger } from '../utils/logger';
import { v4 as uuidv4 } from 'uuid';

/**
 * 监控告警服务
 * 负责监控系统状态并生成告警
 */
export class MonitoringAlertService {
  private static monitoringConfigs: Map<string, MonitoringConfig> = new Map();
  private static monitoringStatus: Map<string, MonitoringStatus> = new Map();
  private static alerts: Map<string, Alert> = new Map();

  /**
   * 配置监控
   * @param config 监控配置
   * @returns 配置结果
   */
  static async configureMonitoring(config: MonitoringConfig): Promise<{ success: boolean; message: string }> {
    try {
      this.monitoringConfigs.set(config.id, config);
      this.monitoringStatus.set(config.id, {
        status: 'ACTIVE',
        lastChecked: new Date(),
        value: 0,
        threshold: config.threshold
      });

      logger.info(`Monitoring config ${config.id} configured successfully`);
      return { success: true, message: 'Monitoring config configured successfully' };
    } catch (error) {
      logger.error(`Error configuring monitoring: ${error}`);
      return { success: false, message: `Error configuring monitoring: ${error}` };
    }
  }

  /**
   * 触发告警
   * @param configId 配置ID
   * @param severity 告警级别
   * @param message 告警消息
   * @returns 告警结果
   */
  static async triggerAlert(configId: string, severity: 'INFO' | 'WARNING' | 'ERROR' | 'CRITICAL', message: string): Promise<{ success: boolean; alertId: string; message: string }> {
    try {
      const config = this.monitoringConfigs.get(configId);
      if (!config) {
        return { success: false, alertId: '', message: 'Monitoring config not found' };
      }

      const alertId = uuidv4();
      const alert: Alert = {
        id: alertId,
        configId,
        severity,
        message,
        status: 'ACTIVE',
        created: new Date(),
        updated: new Date()
      };

      this.alerts.set(alertId, alert);

      // 更新监控状态
      const status = this.monitoringStatus.get(configId);
      if (status) {
        status.lastChecked = new Date();
        status.value = severity === 'CRITICAL' ? 100 : severity === 'ERROR' ? 75 : severity === 'WARNING' ? 50 : 25;
        this.monitoringStatus.set(configId, status);
      }

      logger.info(`Alert ${alertId} triggered for ${configId} with severity ${severity}`);
      return { success: true, alertId, message: 'Alert triggered successfully' };
    } catch (error) {
      logger.error(`Error triggering alert: ${error}`);
      return { success: false, alertId: '', message: `Error triggering alert: ${error}` };
    }
  }

  /**
   * 处理告警
   * @param alertId 告警ID
   * @param action 处理动作
   * @returns 处理结果
   */
  static async handleAlert(alertId: string, action: 'ACKNOWLEDGE' | 'RESOLVE' | 'ESCALATE'): Promise<{ success: boolean; message: string }> {
    try {
      const alert = this.alerts.get(alertId);
      if (!alert) {
        return { success: false, message: 'Alert not found' };
      }

      // 更新告警状态
      switch (action) {
        case 'ACKNOWLEDGE':
          alert.status = 'ACKNOWLEDGED';
          break;
        case 'RESOLVE':
          alert.status = 'RESOLVED';
          break;
        case 'ESCALATE':
          alert.status = 'ESCALATED';
          break;
      }

      alert.updated = new Date();
      this.alerts.set(alertId, alert);

      logger.info(`Alert ${alertId} handled with action ${action}`);
      return { success: true, message: 'Alert handled successfully' };
    } catch (error) {
      logger.error(`Error handling alert: ${error}`);
      return { success: false, message: `Error handling alert: ${error}` };
    }
  }

  /**
   * 获取监控状态
   * @param configId 配置ID
   * @returns 监控状态
   */
  static async getMonitoringStatus(configId: string): Promise<MonitoringStatus | null> {
    try {
      const status = this.monitoringStatus.get(configId);
      if (!status) {
        return null;
      }

      // 模拟更新监控值
      status.lastChecked = new Date();
      status.value = Math.floor(Math.random() * 100);
      this.monitoringStatus.set(configId, status);

      return status;
    } catch (error) {
      logger.error(`Error getting monitoring status: ${error}`);
      return null;
    }
  }

  /**
   * 列出所有监控配置
   * @returns 监控配置列表
   */
  static async listMonitoringConfigs(): Promise<Array<{ id: string; config: MonitoringConfig; status: MonitoringStatus }>> {
    try {
      const configs: Array<{ id: string; config: MonitoringConfig; status: MonitoringStatus }> = [];

      for (const [id, config] of this.monitoringConfigs.entries()) {
        const status = this.monitoringStatus.get(id) || {
          status: 'INACTIVE',
          lastChecked: new Date(),
          value: 0,
          threshold: config.threshold
        };
        configs.push({ id, config, status });
      }

      return configs;
    } catch (error) {
      logger.error(`Error listing monitoring configs: ${error}`);
      return [];
    }
  }

  /**
   * 列出所有告警
   * @param status 告警状态（可选）
   * @returns 告警列表
   */
  static async listAlerts(status?: AlertStatus): Promise<Alert[]> {
    try {
      const alerts: Alert[] = [];

      for (const alert of this.alerts.values()) {
        if (!status || alert.status === status) {
          alerts.push(alert);
        }
      }

      // 按时间倒序排序
      alerts.sort((a, b) => b.created.getTime() - a.created.getTime());

      return alerts;
    } catch (error) {
      logger.error(`Error listing alerts: ${error}`);
      return [];
    }
  }

  /**
   * 删除监控配置
   * @param configId 配置ID
   * @returns 删除结果
   */
  static async deleteMonitoringConfig(configId: string): Promise<{ success: boolean; message: string }> {
    try {
      const config = this.monitoringConfigs.get(configId);
      if (!config) {
        return { success: false, message: 'Monitoring config not found' };
      }

      this.monitoringConfigs.delete(configId);
      this.monitoringStatus.delete(configId);

      // 删除相关告警
      for (const [alertId, alert] of this.alerts.entries()) {
        if (alert.configId === configId) {
          this.alerts.delete(alertId);
        }
      }

      logger.info(`Monitoring config ${configId} deleted successfully`);
      return { success: true, message: 'Monitoring config deleted successfully' };
    } catch (error) {
      logger.error(`Error deleting monitoring config: ${error}`);
      return { success: false, message: `Error deleting monitoring config: ${error}` };
    }
  }

  /**
   * 删除告警
   * @param alertId 告警ID
   * @returns 删除结果
   */
  static async deleteAlert(alertId: string): Promise<{ success: boolean; message: string }> {
    try {
      const alert = this.alerts.get(alertId);
      if (!alert) {
        return { success: false, message: 'Alert not found' };
      }

      this.alerts.delete(alertId);

      logger.info(`Alert ${alertId} deleted successfully`);
      return { success: true, message: 'Alert deleted successfully' };
    } catch (error) {
      logger.error(`Error deleting alert: ${error}`);
      return { success: false, message: `Error deleting alert: ${error}` };
    }
  }

  /**
   * 执行监控检查
   * @param configId 配置ID
   * @returns 检查结果
   */
  static async runMonitoringCheck(configId: string): Promise<{ success: boolean; status: MonitoringStatus; message: string }> {
    try {
      const config = this.monitoringConfigs.get(configId);
      if (!config) {
        return { success: false, status: null, message: 'Monitoring config not found' };
      }

      // 模拟监控检查
      await new Promise(resolve => setTimeout(resolve, 500));

      // 生成随机监控值
      const value = Math.floor(Math.random() * 100);
      const status: MonitoringStatus = {
        status: value > config.threshold ? 'ALERT' : 'NORMAL',
        lastChecked: new Date(),
        value,
        threshold: config.threshold
      };

      this.monitoringStatus.set(configId, status);

      // 如果超过阈值，触发告警
      if (value > config.threshold) {
        await this.triggerAlert(configId, 'WARNING', `Monitoring value ${value} exceeds threshold ${config.threshold}`);
      }

      logger.info(`Monitoring check completed for ${configId}, value: ${value}`);
      return { success: true, status, message: 'Monitoring check completed successfully' };
    } catch (error) {
      logger.error(`Error running monitoring check: ${error}`);
      return { success: false, status: null, message: `Error running monitoring check: ${error}` };
    }
  }

  /**
   * 执行所有监控检查
   * @returns 检查结果列表
   */
  static async runAllMonitoringChecks(): Promise<Array<{ configId: string; status: MonitoringStatus }>> {
    try {
      const results: Array<{ configId: string; status: MonitoringStatus }> = [];

      for (const configId of this.monitoringConfigs.keys()) {
        const result = await this.runMonitoringCheck(configId);
        if (result.success && result.status) {
          results.push({ configId, status: result.status });
        }
      }

      return results;
    } catch (error) {
      logger.error(`Error running all monitoring checks: ${error}`);
      return [];
    }
  }

  /**
   * 生成监控报告
   * @returns 监控报告
   */
  static async generateMonitoringReport(): Promise<{ success: boolean; report: any; message: string }> {
    try {
      const configs = await this.listMonitoringConfigs();
      const alerts = await this.listAlerts();

      const report = {
        generatedAt: new Date(),
        summary: {
          totalConfigs: configs.length,
          activeAlerts: alerts.filter(a => a.status === 'ACTIVE').length,
          normalConfigs: configs.filter(c => c.status.status === 'NORMAL').length,
          alertConfigs: configs.filter(c => c.status.status === 'ALERT').length
        },
        details: {
          configs,
          alerts: alerts.slice(0, 10) // 只返回最近的10个告警
        }
      };

      logger.info('Monitoring report generated successfully');
      return { success: true, report, message: 'Monitoring report generated successfully' };
    } catch (error) {
      logger.error(`Error generating monitoring report: ${error}`);
      return { success: false, report: null, message: `Error generating monitoring report: ${error}` };
    }
  }
}
