import { ServiceConfig, ServiceStatus, ServiceHealthCheck } from '../types/service';
import { logger } from '../utils/logger';

/**
 * 服务管理服务
 * 负责管理系统中的所有服务，包括服务的注册、启动、停止、监控等
 */
export class ServiceManagementService {
  private static services: Map<string, ServiceConfig> = new Map();
  private static serviceHealth: Map<string, ServiceStatus> = new Map();

  /**
   * 注册服务
   * @param service 服务配置
   * @returns 注册结果
   */
  static async registerService(service: ServiceConfig): Promise<{ success: boolean; message: string }> {
    try {
      if (this.services.has(service.id)) {
        return { success: false, message: 'Service already registered' };
      }

      this.services.set(service.id, service);
      this.serviceHealth.set(service.id, { status: 'STOPPED', lastCheck: new Date() });

      logger.info(`Service ${service.id} registered successfully`);
      return { success: true, message: 'Service registered successfully' };
    } catch (error) {
      logger.error(`Error registering service: ${error}`);
      return { success: false, message: `Error registering service: ${error}` };
    }
  }

  /**
   * 启动服务
   * @param serviceId 服务ID
   * @returns 启动结果
   */
  static async startService(serviceId: string): Promise<{ success: boolean; message: string }> {
    try {
      const service = this.services.get(serviceId);
      if (!service) {
        return { success: false, message: 'Service not found' };
      }

      // 模拟服务启动
      await new Promise(resolve => setTimeout(resolve, 1000));

      this.serviceHealth.set(serviceId, { status: 'RUNNING', lastCheck: new Date() });
      logger.info(`Service ${serviceId} started successfully`);
      return { success: true, message: 'Service started successfully' };
    } catch (error) {
      logger.error(`Error starting service: ${error}`);
      return { success: false, message: `Error starting service: ${error}` };
    }
  }

  /**
   * 停止服务
   * @param serviceId 服务ID
   * @returns 停止结果
   */
  static async stopService(serviceId: string): Promise<{ success: boolean; message: string }> {
    try {
      const service = this.services.get(serviceId);
      if (!service) {
        return { success: false, message: 'Service not found' };
      }

      // 模拟服务停止
      await new Promise(resolve => setTimeout(resolve, 500));

      this.serviceHealth.set(serviceId, { status: 'STOPPED', lastCheck: new Date() });
      logger.info(`Service ${serviceId} stopped successfully`);
      return { success: true, message: 'Service stopped successfully' };
    } catch (error) {
      logger.error(`Error stopping service: ${error}`);
      return { success: false, message: `Error stopping service: ${error}` };
    }
  }

  /**
   * 获取服务状态
   * @param serviceId 服务ID
   * @returns 服务状态
   */
  static async getServiceStatus(serviceId: string): Promise<ServiceStatus | null> {
    try {
      const status = this.serviceHealth.get(serviceId);
      if (!status) {
        return null;
      }

      // 更新最后检查时间
      status.lastCheck = new Date();
      this.serviceHealth.set(serviceId, status);

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

  /**
   * 获取所有服务列表
   * @returns 服务列表
   */
  static async listServices(): Promise<Array<{ id: string; config: ServiceConfig; status: ServiceStatus }>> {
    try {
      const services: Array<{ id: string; config: ServiceConfig; status: ServiceStatus }> = [];

      for (const [id, config] of this.services.entries()) {
        const status = this.serviceHealth.get(id) || { status: 'UNKNOWN', lastCheck: new Date() };
        services.push({ id, config, status });
      }

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

  /**
   * 检查服务健康状态
   * @param serviceId 服务ID
   * @returns 健康检查结果
   */
  static async checkServiceHealth(serviceId: string): Promise<ServiceHealthCheck> {
    try {
      const service = this.services.get(serviceId);
      if (!service) {
        return {
          serviceId,
          status: 'ERROR',
          message: 'Service not found',
          timestamp: new Date()
        };
      }

      const status = this.serviceHealth.get(serviceId);
      if (!status) {
        return {
          serviceId,
          status: 'ERROR',
          message: 'Service status not found',
          timestamp: new Date()
        };
      }

      // 模拟健康检查
      const isHealthy = status.status === 'RUNNING';

      return {
        serviceId,
        status: isHealthy ? 'HEALTHY' : 'UNHEALTHY',
        message: isHealthy ? 'Service is running normally' : 'Service is not running',
        timestamp: new Date()
      };
    } catch (error) {
      logger.error(`Error checking service health: ${error}`);
      return {
        serviceId,
        status: 'ERROR',
        message: `Error checking health: ${error}`,
        timestamp: new Date()
      };
    }
  }

  /**
   * 检查所有服务健康状态
   * @returns 健康检查结果列表
   */
  static async checkAllServicesHealth(): Promise<ServiceHealthCheck[]> {
    try {
      const healthChecks: ServiceHealthCheck[] = [];

      for (const serviceId of this.services.keys()) {
        const healthCheck = await this.checkServiceHealth(serviceId);
        healthChecks.push(healthCheck);
      }

      return healthChecks;
    } catch (error) {
      logger.error(`Error checking all services health: ${error}`);
      return [];
    }
  }

  /**
   * 重启服务
   * @param serviceId 服务ID
   * @returns 重启结果
   */
  static async restartService(serviceId: string): Promise<{ success: boolean; message: string }> {
    try {
      // 先停止服务
      const stopResult = await this.stopService(serviceId);
      if (!stopResult.success) {
        return stopResult;
      }

      // 再启动服务
      return await this.startService(serviceId);
    } catch (error) {
      logger.error(`Error restarting service: ${error}`);
      return { success: false, message: `Error restarting service: ${error}` };
    }
  }

  /**
   * 卸载服务
   * @param serviceId 服务ID
   * @returns 卸载结果
   */
  static async unregisterService(serviceId: string): Promise<{ success: boolean; message: string }> {
    try {
      const service = this.services.get(serviceId);
      if (!service) {
        return { success: false, message: 'Service not found' };
      }

      // 先停止服务
      await this.stopService(serviceId);

      // 移除服务
      this.services.delete(serviceId);
      this.serviceHealth.delete(serviceId);

      logger.info(`Service ${serviceId} unregistered successfully`);
      return { success: true, message: 'Service unregistered successfully' };
    } catch (error) {
      logger.error(`Error unregistering service: ${error}`);
      return { success: false, message: `Error unregistering service: ${error}` };
    }
  }
}
