"""Input format parsers and parser registry for words-to-readlang.

This module provides the parser registry system that allows parsers to be
registered and discovered at runtime. New parsers can be added by implementing
the Parser protocol and using the @register_parser decorator.
"""

from typing import Dict, Type

from .base import Parser

# Registry of all available parsers: {name: ParserClass}
_PARSERS: Dict[str, Type[Parser]] = {}


def register_parser(name: str):
    """Decorator to register a parser in the global registry.

    Args:
        name: The name to register this parser under (used in CLI and API)

    Returns:
        A decorator function that registers the parser class

    Example:
        >>> @register_parser("myformat")
        ... class MyFormatParser:
        ...     @property
        ...     def name(self) -> str:
        ...         return "myformat"
        ...
        ...     @property
        ...     def description(self) -> str:
        ...         return "My custom format"
        ...
        ...     def parse(self, file_path: Path) -> List[Entry]:
        ...         # Implementation here
        ...         pass
    """

    def decorator(cls: Type[Parser]):
        _PARSERS[name] = cls
        return cls

    return decorator


def get_parser(name: str) -> Parser:
    """Get a parser instance by name.

    Args:
        name: The registered name of the parser (e.g., 'pod101', 'languagereactor')

    Returns:
        An instance of the requested parser

    Raises:
        ValueError: If no parser with the given name is registered

    Example:
        >>> parser = get_parser("pod101")
        >>> entries = parser.parse(Path("words.csv"))
    """
    if name not in _PARSERS:
        available = ", ".join(sorted(_PARSERS.keys()))
        raise ValueError(
            f"Unknown parser: '{name}'. Available parsers: {available}"
        )

    return _PARSERS[name]()


def list_parsers() -> Dict[str, str]:
    """Return dict of {name: description} for all registered parsers.

    Returns:
        Dictionary mapping parser names to their descriptions

    Example:
        >>> parsers = list_parsers()
        >>> print(parsers["pod101"])
        'Pod101 vocabulary export (UTF-16 CSV with Word,English columns)'
    """
    return {name: cls().description for name, cls in _PARSERS.items()}


# Import and register built-in parsers
# This must come after the registry functions are defined
from .languagereactor import LanguageReactorParser
from .pod101 import Pod101Parser

register_parser("pod101")(Pod101Parser)
register_parser("languagereactor")(LanguageReactorParser)
register_parser("lr")(LanguageReactorParser)  # Shortcut for languagereactor

__all__ = ["Parser", "get_parser", "list_parsers", "register_parser"]
