import { DomainEventBus } from '../runtime/DomainEventBus';
import { ServiceRegistry } from '../orchestrator/ServiceRegistry';

// 开发者信息
export interface Developer {
  id: string;
  name: string;
  email: string;
  apiKey: string;
  createdAt: Date;
  lastActive: Date;
  status: 'active' | 'inactive' | 'suspended';
  permissions: string[];
  metadata?: Record<string, any>;
}

// 插件信息
export interface Plugin {
  id: string;
  name: string;
  version: string;
  description: string;
  developerId: string;
  type: 'adapter' | 'service' | 'UI' | 'integration';
  status: 'pending' | 'approved' | 'rejected' | 'published';
  dependencies: string[];
  entryPoint: string;
  createdAt: Date;
  lastUpdated: Date;
  metadata?: Record<string, any>;
}

// API密钥
export interface ApiKey {
  id: string;
  developerId: string;
  key: string;
  name: string;
  permissions: string[];
  createdAt: Date;
  expiresAt: Date;
  status: 'active' | 'revoked' | 'expired';
}

// 开发者平台
export class DeveloperPlatform {
  private static instance: DeveloperPlatform;
  private developers: Map<string, Developer> = new Map();
  private plugins: Map<string, Plugin> = new Map();
  private apiKeys: Map<string, ApiKey> = new Map();
  private serviceRegistry: ServiceRegistry;
  private eventBus: DomainEventBus;

  private constructor() {
    this.serviceRegistry = ServiceRegistry.getInstance();
    this.eventBus = DomainEventBus.getInstance();
  }

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

  // 注册开发者
  async registerDeveloper(developer: Omit<Developer, 'id' | 'createdAt' | 'lastActive' | 'apiKey'>): Promise<Developer> {
    const id = `dev_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const apiKey = this.generateApiKey();
    
    const newDeveloper: Developer = {
      ...developer,
      id,
      apiKey,
      createdAt: new Date(),
      lastActive: new Date()
    };

    this.developers.set(id, newDeveloper);
    this.eventBus.publish('developer.registered', newDeveloper);
    return newDeveloper;
  }

  // 获取开发者信息
  getDeveloper(developerId: string): Developer | undefined {
    return this.developers.get(developerId);
  }

  // 获取所有开发者
  getAllDevelopers(): Developer[] {
    return Array.from(this.developers.values());
  }

  // 更新开发者信息
  async updateDeveloper(developerId: string, updates: Partial<Developer>): Promise<Developer | null> {
    const developer = this.developers.get(developerId);
    if (!developer) {
      return null;
    }

    const updatedDeveloper = {
      ...developer,
      ...updates,
      lastActive: new Date()
    };

    this.developers.set(developerId, updatedDeveloper);
    this.eventBus.publish('developer.updated', updatedDeveloper);
    return updatedDeveloper;
  }

  // 停用开发者
  async deactivateDeveloper(developerId: string): Promise<boolean> {
    const developer = this.developers.get(developerId);
    if (!developer) {
      return false;
    }

    developer.status = 'inactive';
    developer.lastActive = new Date();
    this.developers.set(developerId, developer);
    this.eventBus.publish('developer.deactivated', developer);
    return true;
  }

  // 注册插件
  async registerPlugin(plugin: Omit<Plugin, 'id' | 'createdAt' | 'lastUpdated' | 'status'>): Promise<Plugin> {
    const id = `plugin_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    
    const newPlugin: Plugin = {
      ...plugin,
      id,
      status: 'pending',
      createdAt: new Date(),
      lastUpdated: new Date()
    };

    this.plugins.set(id, newPlugin);
    this.eventBus.publish('plugin.registered', newPlugin);
    return newPlugin;
  }

  // 获取插件信息
  getPlugin(pluginId: string): Plugin | undefined {
    return this.plugins.get(pluginId);
  }

  // 获取所有插件
  getAllPlugins(): Plugin[] {
    return Array.from(this.plugins.values());
  }

  // 获取开发者的插件
  getDeveloperPlugins(developerId: string): Plugin[] {
    return Array.from(this.plugins.values()).filter(p => p.developerId === developerId);
  }

  // 审核插件
  async reviewPlugin(pluginId: string, status: 'approved' | 'rejected', reason?: string): Promise<Plugin | null> {
    const plugin = this.plugins.get(pluginId);
    if (!plugin) {
      return null;
    }

    plugin.status = status;
    plugin.lastUpdated = new Date();
    if (reason) {
      plugin.metadata = {
        ...plugin.metadata,
        reviewReason: reason
      };
    }

    this.plugins.set(pluginId, plugin);
    this.eventBus.publish('plugin.reviewed', plugin);
    
    if (status === 'approved') {
      // 发布插件
      plugin.status = 'published';
      this.eventBus.publish('plugin.published', plugin);
    }

    return plugin;
  }

  // 生成API密钥
  async generateApiKey(developerId: string, name: string, permissions: string[], expiresInDays: number = 365): Promise<ApiKey> {
    const developer = this.developers.get(developerId);
    if (!developer) {
      throw new Error('Developer not found');
    }

    const id = `apikey_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const key = this.generateApiKey();
    const expiresAt = new Date();
    expiresAt.setDate(expiresAt.getDate() + expiresInDays);

    const apiKey: ApiKey = {
      id,
      developerId,
      key,
      name,
      permissions,
      createdAt: new Date(),
      expiresAt,
      status: 'active'
    };

    this.apiKeys.set(id, apiKey);
    this.eventBus.publish('apiKey.created', apiKey);
    return apiKey;
  }

  // 验证API密钥
  validateApiKey(apiKey: string): ApiKey | null {
    const key = Array.from(this.apiKeys.values()).find(k => k.key === apiKey && k.status === 'active' && k.expiresAt > new Date());
    return key || null;
  }

  // 撤销API密钥
  async revokeApiKey(apiKeyId: string): Promise<boolean> {
    const apiKey = this.apiKeys.get(apiKeyId);
    if (!apiKey) {
      return false;
    }

    apiKey.status = 'revoked';
    this.apiKeys.set(apiKeyId, apiKey);
    this.eventBus.publish('apiKey.revoked', apiKey);
    return true;
  }

  // 获取开发者的API密钥
  getDeveloperApiKeys(developerId: string): ApiKey[] {
    return Array.from(this.apiKeys.values()).filter(k => k.developerId === developerId);
  }

  // 生成API密钥
  private generateApiKey(): string {
    return `sk_${Math.random().toString(36).substr(2, 32)}`;
  }

  // 导入插件
  async importPlugin(pluginData: any): Promise<Plugin> {
    // 这里应该有插件导入逻辑
    // 暂时返回一个模拟的插件
    return this.registerPlugin({
      name: pluginData.name,
      version: pluginData.version,
      description: pluginData.description,
      developerId: pluginData.developerId,
      type: pluginData.type || 'service',
      dependencies: pluginData.dependencies || [],
      entryPoint: pluginData.entryPoint
    });
  }

  // 导出插件
  async exportPlugin(pluginId: string): Promise<any> {
    const plugin = this.plugins.get(pluginId);
    if (!plugin) {
      throw new Error('Plugin not found');
    }

    // 这里应该有插件导出逻辑
    // 暂时返回插件信息
    return {
      ...plugin,
      developer: this.developers.get(plugin.developerId)
    };
  }
}
