// 字段控件覆盖机制
// 约定：/src/apps/<app>/<module>/pagetype/<pagetype>/form/controls/<fieldtype>.vue

type AsyncComponentLoader = () => Promise<any>

// 扫描所有可能的控件覆盖组件
const allControlOverrides: Record<string, AsyncComponentLoader> = import.meta.glob(
  '/src/apps/**/pagetype/**/form/controls/**.vue'
)

/**
 * 解析并返回指定 pagetype 和 fieldtype 的控件覆盖组件
 * @param entity pagetype名称
 * @param fieldtype 字段类型
 */
export async function resolveControlOverride(entity: string, fieldtype: string): Promise<any | null> {
  if (!entity || !fieldtype) return null
  
  // 将entity转换为下划线格式（与文件系统一致）
  const entityUnderscore = entity.toLowerCase().replace(/-/g, '_')
  const fieldtypeNormalized = fieldtype.replace(/\s+/g, '')
  
  // 构建目标路径模式
  const targetPattern = `/src/apps/**/pagetype/${entityUnderscore}/form/controls/${fieldtypeNormalized}.vue`
  
  // 查找匹配的控件覆盖
  const candidates = Object.keys(allControlOverrides).filter((path) => {
    const segments = path.split('/').filter(Boolean)
    const len = segments.length
    
    if (len < 7) return false // 至少需要 7 段路径
    
    // 检查路径结构：.../pagetype/{entity}/form/controls/{fieldtype}.vue
    const pagetypeIndex = segments.findIndex(s => s === 'pagetype')
    if (pagetypeIndex === -1 || pagetypeIndex >= len - 4) return false
    
    const entityInPath = segments[pagetypeIndex + 1]
    const formInPath = segments[pagetypeIndex + 2]
    const controlsInPath = segments[pagetypeIndex + 3]
    const fileName = segments[len - 1]
    
    const fieldtypeInPath = fileName.replace(/\.vue$/i, '')
    
    return (
      entityInPath === entityUnderscore &&
      formInPath === 'form' &&
      controlsInPath === 'controls' &&
      fieldtypeInPath === fieldtypeNormalized
    )
  })
  
  if (candidates.length === 0) return null
  
  // 如果有多个匹配，选择路径最短的（更接近根目录的优先）
  candidates.sort((a, b) => a.length - b.length)
  
  const selectedPath = candidates[0]
  try {
    const module = await allControlOverrides[selectedPath]()
    return module?.default ?? module
  } catch (_e) {
    return null
  }
}
