import { DomainEventBus } from '../runtime/DomainEventBus';
import { ServiceOrchestrator, ServiceStatus } from './ServiceOrchestrator';
import { ServiceRegistry } from './ServiceRegistry';

// 服务监控指标
export interface ServiceMetrics {
  serviceId: string;
  status: ServiceStatus;
  responseTime: number; // 毫秒
  errorRate: number; // 错误率
  throughput: number; // 每秒请求数
  lastHealthCheck: Date;
  uptime: number; // 秒
  memoryUsage?: number; // 内存使用量（MB）
  cpuUsage?: number; // CPU使用率（%）
}

// 服务监控配置
export interface MonitorConfig {
  healthCheckInterval: number; // 健康检查间隔（毫秒）
  metricsCollectionInterval: number; // 指标收集间隔（毫秒）
  alertThresholds: {
    errorRate: number;
    responseTime: number;
    uptime: number;
  };
}

// 服务监控器
export class ServiceMonitor {
  private static instance: ServiceMonitor;
  private serviceOrchestrator: ServiceOrchestrator;
  private serviceRegistry: ServiceRegistry;
  private eventBus: DomainEventBus;
  private metrics: Map<string, ServiceMetrics> = new Map();
  private config: MonitorConfig;
  private healthCheckTimers: Map<string, NodeJS.Timeout> = new Map();
  private metricsCollectionTimer: NodeJS.Timeout | null = null;

  private constructor() {
    this.serviceOrchestrator = ServiceOrchestrator.getInstance();
    this.serviceRegistry = ServiceRegistry.getInstance();
    this.eventBus = DomainEventBus.getInstance();
    
    this.config = {
      healthCheckInterval: 30000, // 30秒
      metricsCollectionInterval: 60000, // 60秒
      alertThresholds: {
        errorRate: 0.1, // 10%
        responseTime: 1000, // 1秒
        uptime: 86400, // 24小时
      }
    };
  }

  static getInstance(): ServiceMonitor {
    if (!ServiceMonitor.instance) {
      ServiceMonitor.instance = new ServiceMonitor();
    }
    return ServiceMonitor.instance;
  }

  // 启动监控
  startMonitoring(): void {
    // 启动指标收集
    this.startMetricsCollection();

    // 为每个服务启动健康检查
    for (const service of this.serviceRegistry.getAllServices()) {
      this.startHealthCheck(service.id);
    }

    // 监听服务注册事件
    this.eventBus.subscribe('service.registered', (data: { serviceId: string }) => {
      this.startHealthCheck(data.serviceId);
    });

    // 监听服务状态变更事件
    this.eventBus.subscribe('service.started', (data: { serviceId: string }) => {
      this.updateMetrics(data.serviceId);
    });

    this.eventBus.subscribe('service.stopped', (data: { serviceId: string }) => {
      this.updateMetrics(data.serviceId);
    });

    this.eventBus.subscribe('service.error', (data: { serviceId: string, error: string }) => {
      this.updateMetrics(data.serviceId);
      this.sendAlert(data.serviceId, `Service error: ${data.error}`);
    });

    this.eventBus.subscribe('service.recovered', (data: { serviceId: string }) => {
      this.updateMetrics(data.serviceId);
      this.sendAlert(data.serviceId, 'Service recovered', 'info');
    });
  }

  // 停止监控
  stopMonitoring(): void {
    // 停止健康检查
    for (const [serviceId, timer] of this.healthCheckTimers) {
      clearInterval(timer);
    }
    this.healthCheckTimers.clear();

    // 停止指标收集
    if (this.metricsCollectionTimer) {
      clearInterval(this.metricsCollectionTimer);
      this.metricsCollectionTimer = null;
    }
  }

  // 启动健康检查
  private startHealthCheck(serviceId: string): void {
    if (this.healthCheckTimers.has(serviceId)) {
      return;
    }

    const timer = setInterval(async () => {
      try {
        const healthy = await this.serviceOrchestrator.healthCheck(serviceId);
        if (!healthy) {
          this.sendAlert(serviceId, 'Service health check failed');
        }
      } catch (error) {
        console.error(`Error checking health for service ${serviceId}:`, error);
      }
    }, this.config.healthCheckInterval);

    this.healthCheckTimers.set(serviceId, timer);
  }

  // 停止健康检查
  private stopHealthCheck(serviceId: string): void {
    const timer = this.healthCheckTimers.get(serviceId);
    if (timer) {
      clearInterval(timer);
      this.healthCheckTimers.delete(serviceId);
    }
  }

  // 启动指标收集
  private startMetricsCollection(): void {
    if (this.metricsCollectionTimer) {
      return;
    }

    this.metricsCollectionTimer = setInterval(() => {
      this.collectMetrics();
    }, this.config.metricsCollectionInterval);
  }

  // 收集指标
  private collectMetrics(): void {
    for (const service of this.serviceRegistry.getAllServices()) {
      this.updateMetrics(service.id);
    }
  }

  // 更新指标
  private updateMetrics(serviceId: string): void {
    const status = this.serviceOrchestrator.getServiceStatus(serviceId);
    if (!status) {
      return;
    }

    const currentMetrics = this.metrics.get(serviceId) || {
      serviceId,
      status: 'stopped' as ServiceStatus,
      responseTime: 0,
      errorRate: 0,
      throughput: 0,
      lastHealthCheck: new Date(),
      uptime: 0
    };

    const newMetrics: ServiceMetrics = {
      ...currentMetrics,
      status,
      lastHealthCheck: new Date(),
      // 这里应该有实际的指标收集逻辑
      // 暂时使用模拟数据
      responseTime: Math.random() * 500,
      errorRate: Math.random() * 0.05,
      throughput: Math.random() * 100,
      uptime: currentMetrics.uptime + (this.config.metricsCollectionInterval / 1000)
    };

    this.metrics.set(serviceId, newMetrics);

    // 检查是否需要告警
    this.checkAlertThresholds(newMetrics);

    // 发布指标更新事件
    this.eventBus.publish('service.metrics.updated', newMetrics);
  }

  // 检查告警阈值
  private checkAlertThresholds(metrics: ServiceMetrics): void {
    if (metrics.errorRate > this.config.alertThresholds.errorRate) {
      this.sendAlert(metrics.serviceId, `High error rate: ${(metrics.errorRate * 100).toFixed(2)}%`);
    }

    if (metrics.responseTime > this.config.alertThresholds.responseTime) {
      this.sendAlert(metrics.serviceId, `High response time: ${metrics.responseTime.toFixed(2)}ms`);
    }

    if (metrics.uptime < this.config.alertThresholds.uptime) {
      this.sendAlert(metrics.serviceId, `Low uptime: ${(metrics.uptime / 3600).toFixed(2)} hours`);
    }
  }

  // 发送告警
  private sendAlert(serviceId: string, message: string, level: 'error' | 'warning' | 'info' = 'error'): void {
    console.log(`[${level.toUpperCase()}] Service ${serviceId}: ${message}`);
    this.eventBus.publish('service.alert', { serviceId, message, level, timestamp: new Date() });
  }

  // 获取服务指标
  getServiceMetrics(serviceId: string): ServiceMetrics | undefined {
    return this.metrics.get(serviceId);
  }

  // 获取所有服务指标
  getAllServiceMetrics(): ServiceMetrics[] {
    return Array.from(this.metrics.values());
  }

  // 获取服务健康状态
  getServiceHealth(serviceId: string): 'healthy' | 'unhealthy' | 'unknown' {
    const metrics = this.metrics.get(serviceId);
    if (!metrics) {
      return 'unknown';
    }

    if (metrics.status === 'running' && metrics.errorRate < 0.05 && metrics.responseTime < 500) {
      return 'healthy';
    }

    return 'unhealthy';
  }

  // 获取所有服务健康状态
  getAllServiceHealth(): Map<string, 'healthy' | 'unhealthy' | 'unknown'> {
    const healthStatus = new Map<string, 'healthy' | 'unhealthy' | 'unknown'>();
    
    for (const service of this.serviceRegistry.getAllServices()) {
      healthStatus.set(service.id, this.getServiceHealth(service.id));
    }

    return healthStatus;
  }

  // 设置监控配置
  setConfig(config: Partial<MonitorConfig>): void {
    this.config = {
      ...this.config,
      ...config
    };
  }

  // 获取监控配置
  getConfig(): MonitorConfig {
    return { ...this.config };
  }
}
