"""
Parser Registry — maps (mime_type, subtype) keys to parser instances.

Usage:
    parser = registry.get("application/pdf", "digital")
    elements = parser.parse(file_record)
"""

from __future__ import annotations

from .errors import UnsupportedFormatError
from .parsers.base import BaseParser


class ParserRegistry:
    """Registry mapping (mime_type, subtype | None) → BaseParser instance."""

    def __init__(self) -> None:
        self._registry: dict[tuple[str, str | None], BaseParser] = {}
        self._fallbacks: dict[tuple[str, str | None], tuple[str, str | None]] = {}

    def register(
        self,
        mime_type: str,
        subtype: str | None,
        parser: BaseParser,
        fallback: tuple[str, str | None] | None = None,
    ) -> None:
        key = (mime_type, subtype)
        self._registry[key] = parser
        if fallback:
            self._fallbacks[key] = fallback

    def get(self, mime_type: str, subtype: str | None = None) -> BaseParser:
        key = (mime_type, subtype)
        parser = self._registry.get(key)
        if parser is None:
            # Try without subtype
            parser = self._registry.get((mime_type, None))
        if parser is None:
            raise UnsupportedFormatError(f"No parser registered for ({mime_type!r}, {subtype!r})")
        return parser

    def get_with_fallback(self, mime_type: str, subtype: str | None = None) -> list[BaseParser]:
        """Return parser chain including fallbacks."""
        key = (mime_type, subtype)
        chain: list[BaseParser] = []
        current = key
        seen: set[tuple[str, str | None]] = set()
        while current not in seen:
            seen.add(current)
            p = self._registry.get(current)
            if p:
                chain.append(p)
            current = self._fallbacks.get(current, ("__stop__", None))
            if current[0] == "__stop__":
                break
        if not chain:
            raise UnsupportedFormatError(f"No parser registered for ({mime_type!r}, {subtype!r})")
        return chain

    def supported_formats(self) -> list[tuple[str, str | None]]:
        return sorted(self._registry.keys())


# Global registry instance — parsers register themselves at import time
registry = ParserRegistry()
