"""
Parser Registry

Manages registration and discovery of API specification parsers.
"""

from typing import Dict, Any, Optional, List
from .base import APISpecParser


class ParserRegistry:
    """
    Registry for API specification parsers.
    
    Maintains a list of registered parsers and provides methods to:
    - Register new parsers
    - Find the appropriate parser for a given spec
    - List all supported formats
    """
    
    def __init__(self, auto_register_builtin: bool = True):
        """
        Initialize the parser registry.
        
        Args:
            auto_register_builtin: If True, automatically register built-in parsers
        """
        self._parsers: List[APISpecParser] = []
        
        if auto_register_builtin:
            self._register_builtin_parsers()
    
    def register(self, parser: APISpecParser) -> None:
        """
        Register a new parser.
        
        Args:
            parser: An instance of APISpecParser to register
        """
        self._parsers.append(parser)
    
    def _register_builtin_parsers(self) -> None:
        """Register all built-in parsers."""
        from .openapi_parser import OpenAPIParser
        
        # Register built-in parsers
        self.register(OpenAPIParser())
        
        # Future parsers will be registered here:
        # from .postman_parser import PostmanCollectionParser
        # self.register(PostmanCollectionParser())
        # from .graphql_parser import GraphQLParser
        # self.register(GraphQLParser())
    
    def find_parser(self, spec_data: Dict[str, Any]) -> Optional[APISpecParser]:
        """
        Find a parser that can handle the given specification.
        
        Parsers are checked in registration order. The first parser that
        returns True from can_parse() is returned.
        
        Args:
            spec_data: The raw specification data as a dictionary
            
        Returns:
            An APISpecParser instance that can handle the spec, or None if
            no suitable parser is found
        """
        for parser in self._parsers:
            if parser.can_parse(spec_data):
                return parser
        return None
    
    def get_supported_formats(self) -> List[str]:
        """
        Get a list of all supported format names.
        
        Returns:
            List of human-readable format names
        """
        return [parser.get_format_name() for parser in self._parsers]
    
    def get_parser_count(self) -> int:
        """
        Get the number of registered parsers.
        
        Returns:
            Number of registered parsers
        """
        return len(self._parsers)
