"""Dynamic action loader - auto-discovers and loads all actions."""

from pathlib import Path
from typing import Dict
from ..action_registry import ActionRegistryImpl, ActionSchema


class DynamicActionLoader:
    """Automatically load all action definitions from directory."""

    def __init__(self, actions_directory: str = None):
        """Initialize loader.
        
        Args:
            actions_directory: Path to actions directory (default: built-in actions)
        """
        if actions_directory is None:
            # Default to built-in actions
            actions_directory = Path(__file__).parent.parent / "action_registry" / "actions"
        
        self.actions_directory = Path(actions_directory)
        self.registry = ActionRegistryImpl()

    def load_all(self) -> ActionRegistryImpl:
        """Load all action files from directory.
        
        Returns:
            Populated ActionRegistryImpl
        """
        if not self.actions_directory.exists():
            raise FileNotFoundError(f"Actions directory not found: {self.actions_directory}")
        
        # Load JSON files
        for json_file in self.actions_directory.glob("*.json"):
            try:
                self.registry.load_from_file(str(json_file))
            except Exception as e:
                print(f"Warning: Failed to load {json_file}: {e}")
        
        # Load YAML files
        for yaml_file in self.actions_directory.glob("*.yaml"):
            try:
                self.registry.load_from_file(str(yaml_file))
            except Exception as e:
                print(f"Warning: Failed to load {yaml_file}: {e}")
        
        for yml_file in self.actions_directory.glob("*.yml"):
            try:
                self.registry.load_from_file(str(yml_file))
            except Exception as e:
                print(f"Warning: Failed to load {yml_file}: {e}")
        
        return self.registry

    def get_action_summary(self) -> Dict[str, list]:
        """Get summary of loaded actions by category.
        
        Returns:
            Dictionary mapping category to list of action IDs
        """
        summary = {}
        for action_id in self.registry.list_actions():
            action = self.registry.get_action(action_id)
            if action.category not in summary:
                summary[action.category] = []
            summary[action.category].append(action_id)
        return summary
