import logger from "@racletteCore/lib/logger"
import { PLUGIN_TYPE_ORDER } from "../constants"
import type { DiscoveredPlugin } from "../types"
import { discoverCorePlugins } from "./core-plugins"
import { discoverAppPlugins } from "./app-plugins"
import { discoverNpmPlugins } from "./npm-plugins"

/**
 * Discover all plugins using static import.meta.glob patterns
 */
export const discoverAllPlugins = async (): Promise<DiscoveredPlugin[]> => {
  const discoveredPlugins: DiscoveredPlugin[] = []

  try {
    // Discover core plugins
    const corePlugins = await discoverCorePlugins()
    discoveredPlugins.push(...corePlugins)

    // Discover app plugins
    const appPlugins = await discoverAppPlugins()
    discoveredPlugins.push(...appPlugins)

    // Discover npm plugins
    const npmPlugins = await discoverNpmPlugins()
    discoveredPlugins.push(...npmPlugins)

    // Sort plugins by type to maintain loading order: core -> npm -> app
    const sortedPlugins = discoveredPlugins.sort((a, b) => {
      return PLUGIN_TYPE_ORDER[a.type] - PLUGIN_TYPE_ORDER[b.type]
    })

    logger.pluginRegistrar(`Found ${sortedPlugins.length} plugins total`)

    return sortedPlugins
  } catch (error) {
    logger.pluginRegistrar("Error during plugin discovery:", error)
    throw error
  }
}

export * from "./core-plugins"
export * from "./app-plugins"
export * from "./npm-plugins"
