import { ServiceDefinition } from './ServiceOrchestrator';

// 服务注册表
export class ServiceRegistry {
  private static instance: ServiceRegistry;
  private services: Map<string, ServiceDefinition> = new Map();
  private serviceIndex: Map<string, string[]> = new Map(); // 按名称索引服务

  private constructor() {}

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

  // 注册服务
  async registerService(service: ServiceDefinition): Promise<void> {
    if (this.services.has(service.id)) {
      throw new Error(`Service with id ${service.id} already exists`);
    }

    this.services.set(service.id, service);

    // 按名称索引
    if (!this.serviceIndex.has(service.name)) {
      this.serviceIndex.set(service.name, []);
    }
    this.serviceIndex.get(service.name)?.push(service.id);
  }

  // 注销服务
  async unregisterService(serviceId: string): Promise<void> {
    const service = this.services.get(serviceId);
    if (!service) {
      throw new Error(`Service ${serviceId} not found`);
    }

    this.services.delete(serviceId);

    // 更新名称索引
    const serviceIds = this.serviceIndex.get(service.name);
    if (serviceIds) {
      const index = serviceIds.indexOf(serviceId);
      if (index !== -1) {
        serviceIds.splice(index, 1);
        if (serviceIds.length === 0) {
          this.serviceIndex.delete(service.name);
        }
      }
    }
  }

  // 获取服务
  getService(serviceId: string): ServiceDefinition | undefined {
    return this.services.get(serviceId);
  }

  // 根据名称获取服务
  getServicesByName(name: string): ServiceDefinition[] {
    const serviceIds = this.serviceIndex.get(name) || [];
    return serviceIds.map(id => this.services.get(id)).filter((s): s is ServiceDefinition => s !== undefined);
  }

  // 获取所有服务
  getAllServices(): ServiceDefinition[] {
    return Array.from(this.services.values());
  }

  // 检查服务是否存在
  hasService(serviceId: string): boolean {
    return this.services.has(serviceId);
  }

  // 获取服务依赖图
  getDependencyGraph(): Map<string, string[]> {
    const graph = new Map<string, string[]>();
    
    for (const [id, service] of this.services) {
      graph.set(id, service.dependencies);
    }
    
    return graph;
  }

  // 验证服务依赖
  validateDependencies(): { valid: boolean; errors: string[] } {
    const errors: string[] = [];
    
    for (const [id, service] of this.services) {
      for (const dependencyId of service.dependencies) {
        if (!this.services.has(dependencyId)) {
          errors.push(`Service ${id} depends on non-existent service ${dependencyId}`);
        }
      }
    }
    
    return {
      valid: errors.length === 0,
      errors
    };
  }

  // 导出服务注册表
  exportRegistry(): Record<string, ServiceDefinition> {
    const registry: Record<string, ServiceDefinition> = {};
    
    for (const [id, service] of this.services) {
      registry[id] = service;
    }
    
    return registry;
  }

  // 导入服务注册表
  async importRegistry(registry: Record<string, ServiceDefinition>): Promise<void> {
    for (const [id, service] of Object.entries(registry)) {
      await this.registerService(service);
    }
  }

  // 清空服务注册表
  clear(): void {
    this.services.clear();
    this.serviceIndex.clear();
  }

  // 获取服务数量
  size(): number {
    return this.services.size;
  }
}
