import os
import sys
import importlib.util
import yaml
from pathlib import Path


class PluginLoader:
    def __init__(self):
        self.plugins_dir = Path.home() / '.feather' / 'plugins'
        self.plugins_dir.mkdir(parents=True, exist_ok=True)
        self.loaded_plugins = {}
    
    def load_plugin(self, plugin_name: str):
        """Load a plugin by name"""
        plugin_path = self.plugins_dir / plugin_name
        
        if not plugin_path.exists():
            print(f"Plugin '{plugin_name}' not found. Run: feather plugin install {plugin_name}")
            return None
        
        config_file = plugin_path / 'plugin.yaml'
        if not config_file.exists():
            print(f"Plugin configuration not found: {config_file}")
            return None
        
        with open(config_file, 'r') as f:
            config = yaml.safe_load(f)
        
        entry_point = config.get('entry_point', '__init__.py')
        module_path = plugin_path / entry_point
        
        if not module_path.exists():
            print(f"Plugin entry point not found: {module_path}")
            return None
        
        spec = importlib.util.spec_from_file_location(plugin_name, module_path)
        module = importlib.util.module_from_spec(spec)
        sys.modules[plugin_name] = module
        spec.loader.exec_module(module)
        
        self.loaded_plugins[plugin_name] = module
        return module
    
    def install_plugin(self, plugin_name: str):
        """Install a plugin from the server"""
        from .installer import PluginInstaller
        installer = PluginInstaller()
        installer.install(plugin_name)
