/**
 * Plugin Registry - 插件註冊中心
 */

import type {
  LeWOOOgoPlugin,
  PluginCategory,
  PluginMetadata,
  HealthStatus,
} from '../interfaces'

export class PluginRegistry {
  private plugins: Map<string, LeWOOOgoPlugin> = new Map()
  private metadata: Map<string, PluginMetadata> = new Map()

  /**
   * 註冊 Plugin
   */
  async register(plugin: LeWOOOgoPlugin): Promise<void> {
    if (this.plugins.has(plugin.id)) {
      throw new Error(`Plugin ${plugin.id} already registered`)
    }

    await plugin.initialize()
    this.plugins.set(plugin.id, plugin)
    this.metadata.set(plugin.id, {
      id: plugin.id,
      name: plugin.name,
      version: plugin.version,
      category: plugin.category,
      description: plugin.description,
    })
  }

  /**
   * 取消註冊 Plugin
   */
  async unregister(pluginId: string): Promise<void> {
    const plugin = this.plugins.get(pluginId)
    if (!plugin) {
      throw new Error(`Plugin ${pluginId} not found`)
    }

    await plugin.shutdown()
    this.plugins.delete(pluginId)
    this.metadata.delete(pluginId)
  }

  /**
   * 取得 Plugin
   */
  get<T extends LeWOOOgoPlugin>(pluginId: string): T | undefined {
    return this.plugins.get(pluginId) as T | undefined
  }

  /**
   * 取得所有 Plugin
   */
  getAll(): LeWOOOgoPlugin[] {
    return Array.from(this.plugins.values())
  }

  /**
   * 按類別取得 Plugin
   */
  getByCategory(category: PluginCategory): LeWOOOgoPlugin[] {
    return this.getAll().filter((p) => p.category === category)
  }

  /**
   * 取得 Plugin 元數據
   */
  getMetadata(pluginId: string): PluginMetadata | undefined {
    return this.metadata.get(pluginId)
  }

  /**
   * 取得所有元數據
   */
  getAllMetadata(): PluginMetadata[] {
    return Array.from(this.metadata.values())
  }

  /**
   * 健康檢查所有 Plugin
   */
  async healthCheckAll(): Promise<Map<string, HealthStatus>> {
    const results = new Map<string, HealthStatus>()

    for (const [id, plugin] of this.plugins) {
      try {
        const status = await plugin.healthCheck()
        results.set(id, status)
      } catch {
        results.set(id, 'unhealthy')
      }
    }

    return results
  }

  /**
   * 關閉所有 Plugin
   */
  async shutdownAll(): Promise<void> {
    for (const plugin of this.plugins.values()) {
      await plugin.shutdown()
    }
    this.plugins.clear()
    this.metadata.clear()
  }
}

// 全域 Registry 實例
export const globalRegistry = new PluginRegistry()
