import { mergeDeepRight } from "ramda"
import logger from "@racletteCore/lib/logger"
import type { PluginFrontendDefinition } from "../types"

/**
 * Load and merge plugin definition from frontend directory
 */
export const loadPluginDefinition = async (
  frontendPath: string,
): Promise<Partial<PluginFrontendDefinition>> => {
  let indexModule: Partial<PluginFrontendDefinition> = {}
  let generatedConfig: { data?: PluginFrontendDefinition["data"] } = {}

  // Create static globs for all possible index and config files
  const indexGlob = import.meta.glob(
    [
      "/src/plugins/**/frontend/index.ts",
      "/src/corePlugins/**/frontend/index.ts",
      "/src/workbenchPlugins/**/frontend/index.ts",
    ],
    { eager: false },
  )

  const configGlob = import.meta.glob(
    [
      "/src/plugins/**/frontend/generated-config.ts",
      "/src/corePlugins/**/frontend/generated-config.ts",
      "/src/workbenchPlugins/**/frontend/generated-config.ts",
    ],
    {
      eager: false,
    },
  )

  // Try to find and load index.ts
  const indexPath = `${frontendPath}/index.ts`
  const matchingIndexFile = Object.keys(indexGlob).find(
    (path) => path === indexPath,
  )

  if (matchingIndexFile) {
    try {
      const importedModule = await indexGlob[matchingIndexFile]()
      indexModule = (importedModule as any)?.default || {}
      logger.pluginRegistrar("Loaded index.ts from", indexPath)
    } catch (error) {
      logger.pluginRegistrar(`Error loading index.ts from ${indexPath}:`, error)
    }
  } else {
    logger.pluginRegistrar(`No index.ts found at`, indexPath)
  }

  // Try to find and load generated-config.ts
  const configPath = `${frontendPath}/generated-config.ts`
  const matchingConfigFile = Object.keys(configGlob).find(
    (path) => path === configPath,
  )

  if (matchingConfigFile) {
    try {
      const importedGenerated = await configGlob[matchingConfigFile]()
      generatedConfig = (importedGenerated as any)?.default || {}

      logger.pluginRegistrar("Loaded generated-config.ts from", configPath)
    } catch (error) {
      logger.pluginRegistrar(
        `Error loading generated-config.ts from ${configPath}:`,
        error,
      )
    }
  } else {
    logger.pluginRegistrar(`No generated-config.ts found at `, configPath)
  }

  // Merge configurations (generated-config as base, index overrides)
  const mergedDefinition = {
    ...indexModule,
    data: mergeDeepRight(generatedConfig.data ?? {}, indexModule.data ?? {}),
  }

  return mergedDefinition
}

export const defineRaclettePluginFrontend = (
  pluginClientDefinition: Partial<PluginFrontendDefinition>,
): Partial<PluginFrontendDefinition> => pluginClientDefinition
