import { generatePluginKey } from "@shared/helper/pluginHelper"
import logger from "@racletteCore/lib/logger"
import { validatePluginMetadata } from "../utils/operations"
import type { DiscoveredPlugin, PluginType } from "../types"

/**
 * Discover core plugins using static glob pattern
 */
export const discoverCorePlugins = async (): Promise<DiscoveredPlugin[]> => {
  const plugins: DiscoveredPlugin[] = []

  try {
    const configModules = import.meta.glob(
      "/src/corePlugins/**/raclette.plugin.ts",
      {
        eager: false,
      },
    )

    for (const configPath of Object.keys(configModules)) {
      try {
        const configModule = await configModules[configPath]()
        const metadata = (configModule as any)?.default || configModule

        if (!validatePluginMetadata(metadata)) {
          logger.pluginRegistrar(`Invalid plugin metadata in ${configPath}`)
          continue
        }

        const pluginPath = configPath.replace(/\/raclette\.plugin\.ts$/, "")
        const frontendRelativePath =
          metadata.frontendDir?.replace(/^\.\//, "") || "frontend"
        const frontendPath = `${pluginPath}/${frontendRelativePath}`

        const pluginKey = generatePluginKey(metadata.name, metadata.author)

        plugins.push({
          configPath,
          pluginPath,
          frontendPath,
          type: "core" as PluginType,
          metadata,
          pluginKey,
        })

        logger.pluginRegistrar("Discovered core plugin", pluginKey)
      } catch (error) {
        logger.pluginRegistrar(
          `Error processing core plugin ${configPath}:`,
          error,
        )
      }
    }
  } catch (error) {
    logger.pluginRegistrar(`Error discovering core plugins:`, error)
  }

  return plugins
}
