// Auto-load pagetype plugins
// Convention: /views/pagetype/<pagetype>/plugins/*.ts
// Convention: /plugins/*.ts (global)

import { registerPagetypePlugin, registerGlobalPlugin, registerRecordInitPlugin, FieldChangePlugin, RecordInitPlugin } from './fieldPlugin'
import { slugToPageType } from '@/shared/utils/slug'

type PluginLoader = () => Promise<any>

// Scan pagetype plugins across all apps
const pagetypePluginGlob = import.meta.glob('@apps/*/frontend/src/views/pagetype/**/plugins/*.ts')
const localPagetypePluginGlob = import.meta.glob('/src/views/pagetype/**/plugins/*.ts')

// Scan global plugins
const globalPluginGlob = import.meta.glob('@apps/*/frontend/src/shared/plugins/*.ts')
const localGlobalPluginGlob = import.meta.glob('/src/shared/plugins/*.ts')

interface PluginModule {
  default?: FieldChangePlugin | FieldChangePlugin[] | RecordInitPlugin | RecordInitPlugin[]
  recordInit?: RecordInitPlugin | RecordInitPlugin[]
}

// Extract pagetype from path
function extractPagetype(path: string): string | null {
  const segs = path.split('/').filter(Boolean)
  const idxPagetype = segs.indexOf('pagetype')
  if (idxPagetype < 0 || idxPagetype + 1 >= segs.length) return null
  
  // Convert directory name (slug) to PageType name
  // Example: stock_entry -> stock-entry -> Stock Entry
  const dirName = segs[idxPagetype + 1]
  return slugToPageType(dirName.replace(/_/g, '-'))
}

// Extract app name from path
function extractAppName(path: string): string {
  const s = path.replace(/\\/g, '/')
  if (s.startsWith('/src/')) return 'jingrow'
  const m = s.match(/(?:^|\/)(?:@?apps)\/([^/]+)\//)
  return m?.[1] || 'jingrow'
}

// Loaded flag
let loaded = false

// Load all plugins
export async function loadAllPlugins(): Promise<void> {
  if (loaded) return
  loaded = true

  // Load pagetype plugins
  const allPagetypePlugins: Record<string, PluginLoader> = {
    ...pagetypePluginGlob,
    ...localPagetypePluginGlob
  }

  for (const [path, loader] of Object.entries(allPagetypePlugins)) {
    const pagetype = extractPagetype(path)
    if (!pagetype) continue

    try {
      const mod: PluginModule = await loader()
      const plugins = mod.default
      if (!plugins) continue

      if (Array.isArray(plugins)) {
        plugins.forEach(p => {
          // Check if it's a RecordInitPlugin (has 'pagetype' property) or FieldChangePlugin (has 'fieldname' property)
          if ('pagetype' in p) {
            registerRecordInitPlugin(p)
          } else {
            registerPagetypePlugin(pagetype, p)
          }
        })
      } else {
        if ('pagetype' in plugins) {
          registerRecordInitPlugin(plugins)
        } else {
          registerPagetypePlugin(pagetype, plugins)
        }
      }
    } catch (err) {
      console.error(`[PluginLoader] Failed to load plugin from ${path}:`, err)
    }
  }

  // Load global plugins
  const allGlobalPlugins: Record<string, PluginLoader> = {
    ...globalPluginGlob,
    ...localGlobalPluginGlob
  }

  for (const [path, loader] of Object.entries(allGlobalPlugins)) {
    try {
      const mod: PluginModule = await loader()
      const plugins = mod.default
      if (!plugins) continue

      if (Array.isArray(plugins)) {
        plugins.forEach(p => {
          if ('pagetype' in p) {
            registerRecordInitPlugin(p)
          } else {
            registerGlobalPlugin(p)
          }
        })
      } else {
        if ('pagetype' in plugins) {
          registerRecordInitPlugin(plugins)
        } else {
          registerGlobalPlugin(plugins)
        }
      }
    } catch (err) {
      console.error(`[PluginLoader] Failed to load global plugin from ${path}:`, err)
    }
  }
}
