"""Font registration for neoplot.

Scans the bundled ``fonts/`` directory for TTF files and registers them with
matplotlib's font manager so they are available by family name (e.g.
``"Montserrat"``, ``"Karma"``).

Custom fonts can be added by placing ``.ttf`` files in the same directory or
by calling :func:`register_fonts` with an alternative path.
"""

from pathlib import Path
from typing import Optional

import matplotlib.font_manager as fm

_FONTS_DIR = Path(__file__).parent / "fonts"

# Track whether the bundled fonts have already been registered to avoid
# redundant scans on repeated imports.
_bundled_registered: bool = False


def register_fonts(fonts_dir: Optional[Path] = None) -> int:
    """Register all ``.ttf`` files found in *fonts_dir* with matplotlib.

    Args:
        fonts_dir: Directory to scan.  Defaults to the bundled ``fonts/``
            directory shipped with neoplot.

    Returns:
        Number of font files registered in this call.
    """
    global _bundled_registered

    directory = Path(fonts_dir) if fonts_dir is not None else _FONTS_DIR
    if not directory.exists():
        return 0

    # Skip if we've already registered the bundled dir (saves repeated work on
    # each import).
    if fonts_dir is None and _bundled_registered:
        return 0

    count = 0
    for ttf in sorted(directory.rglob("*.ttf")):
        fm.fontManager.addfont(str(ttf))
        count += 1

    if fonts_dir is None:
        _bundled_registered = True

    return count


def available_families() -> list:
    """Return all font family names currently known to matplotlib.

    Useful for confirming that a font was successfully registered.
    """
    return sorted({f.name for f in fm.fontManager.ttflist})


def is_available(family: str) -> bool:
    """Return True if *family* is known to matplotlib's font manager."""
    return family in {f.name for f in fm.fontManager.ttflist}
