import { ref, onMounted } from 'vue'

/**
 * Simple composable to handle module loading and readiness
 * Uses Vue's reactivity system - no polling, no complex logic
 */
export function useModuleReady(moduleName: string) {
  const isReady = ref(false)
  const isLoading = ref(true)
  const error = ref<string | null>(null)

  onMounted(async () => {
    try {
      // Dynamic import to avoid circular dependencies
      const { pluginManager } = await import('@/core/plugin-manager')
      
      // Install module if not already installed  
      if (!pluginManager.isInstalled(moduleName)) {
        console.log(`🔄 Installing ${moduleName} module...`)
        await pluginManager.install(moduleName)
      }
      
      // Module is ready - Vue reactivity handles the rest
      isReady.value = true
      console.log(`✅ ${moduleName} module ready`)
      
    } catch (err) {
      console.error(`❌ Failed to load ${moduleName} module:`, err)
      error.value = err instanceof Error ? err.message : 'Failed to load module'
    } finally {
      isLoading.value = false
    }
  })

  return {
    isReady,
    isLoading, 
    error
  }
}