"""``wikitext-base@v1`` π*: wraps :func:`arborist.wikitext.to_base`.

Domain: ``text-or-wikitext``. Input bytes are interpreted as UTF-8;
output bytes are UTF-8 of the canonical prose. ``to_base`` is the
existing wikitext-to-prose canonicalizer; this module is the registry-
facing wrapper. Imports lazily so the optional ``mwparserfromhell``
dep stays optional.
"""

from __future__ import annotations

from dataclasses import dataclass

from arborist.pi_star.protocol import PiStarError
from arborist.pi_star.registry import register


@dataclass
class WikitextBaseV1:
    name: str = "wikitext-base"
    version: str = "v1"
    domain: str = "text-or-wikitext"

    def canonicalize(self, raw: bytes) -> bytes:
        if not isinstance(raw, (bytes, bytearray)):
            raise PiStarError(
                "wikitext-base@v1 expects bytes; got "
                f"{type(raw).__name__}"
            )
        try:
            text = raw.decode("utf-8", errors="surrogatepass")
        except UnicodeDecodeError as exc:  # pragma: no cover — defensive
            raise PiStarError(f"input not valid UTF-8: {exc}") from exc

        # Lazy import — mwparserfromhell is an optional install.
        from arborist.wikitext import to_base

        prose = to_base(text)
        return prose.encode("utf-8", errors="surrogatepass")


register(WikitextBaseV1())
