"""Concrete implementation of ActionRegistry."""

import json
import yaml
from pathlib import Path
from typing import Dict, Any, List, Optional
from .action_schema import ActionSchema


class ActionRegistryImpl:
    """Implementation of action registry."""

    def __init__(self):
        self._actions: Dict[str, ActionSchema] = {}

    def load_from_file(self, file_path: str) -> None:
        """Load actions from JSON or YAML file.
        
        Args:
            file_path: Path to action definition file
        """
        path = Path(file_path)
        
        with open(path, 'r') as f:
            if path.suffix in ['.yaml', '.yml']:
                data = yaml.safe_load(f)
            elif path.suffix == '.json':
                data = json.load(f)
            else:
                raise ValueError(f"Unsupported file format: {path.suffix}")
        
        if 'actions' in data:
            for action_data in data['actions']:
                action = ActionSchema(**action_data)
                self._actions[action.action_id] = action
        else:
            action = ActionSchema(**data)
            self._actions[action.action_id] = action

    def load_from_dict(self, action_data: Dict[str, Any]) -> None:
        """Load action from dictionary.
        
        Args:
            action_data: Action definition dictionary
        """
        action = ActionSchema(**action_data)
        self._actions[action.action_id] = action

    def get_action(self, action_id: str) -> Optional[ActionSchema]:
        """Get action by ID.
        
        Args:
            action_id: Action identifier
            
        Returns:
            ActionSchema or None
        """
        return self._actions.get(action_id)

    def list_actions(self) -> List[str]:
        """List all registered action IDs.
        
        Returns:
            List of action identifiers
        """
        return list(self._actions.keys())

    def validate_params(self, action_id: str, params: Dict[str, Any]) -> tuple[bool, List[str]]:
        """Validate parameters for action.
        
        Args:
            action_id: Action identifier
            params: Parameters to validate
            
        Returns:
            Tuple of (is_valid, missing_params)
        """
        action = self.get_action(action_id)
        if not action:
            return False, [f"Action {action_id} not found"]
        
        missing = [p for p in action.required_params if p not in params]
        return len(missing) == 0, missing

    def get_by_category(self, category: str) -> List[ActionSchema]:
        """Get actions by category.
        
        Args:
            category: Category name
            
        Returns:
            List of actions in category
        """
        return [a for a in self._actions.values() if a.category == category]
