"""Optional integration with biblelib for BCVID reference canonicalization.

biblelib (Clear-Bible/Biblelib, PyPI v0.5.4) provides:
  - BCVID (Book-Chapter-Verse ID) reference parsing and rendering
  - Multi-language book names via ISO 639-3 codes
  - Standardized versification data
  - Book lookup across USFM, OSIS, Biblia, and full-name schemes

Install: pip install biblelib

This module works when biblelib is NOT installed — it simply reports
that biblelib is unavailable.
"""

from __future__ import annotations

import logging

logger = logging.getLogger(__name__)

_BIBLELIB_AVAILABLE = False
try:
    from biblelib.book import Books, get_localized_books  # noqa: F401

    _BIBLELIB_AVAILABLE = True
except ImportError:
    pass


class BibleLibBridge:
    """Bridge between Accordance Port references and biblelib BCVID.

    Provides:
      - resolve_book:  name → OSIS ID (any language, any scheme)
      - get_book_names: OSIS ID → all known names
      - validate_reference: check chapter/verse bounds against versification
    """

    def __init__(self) -> None:
        if not _BIBLELIB_AVAILABLE:
            raise ImportError(
                "biblelib is not installed. Install with: pip install biblelib"
            )
        self._books = Books()

    # ------------------------------------------------------------------
    # Book resolution
    # ------------------------------------------------------------------

    def resolve_book(self, name: str, language: str = "eng") -> str | None:
        """Resolve a book name in any language to standard OSIS ID.

        Uses biblelib's findbook which searches all schemes:
        USFM (``GEN``), OSIS (``Gen``), Biblia (``Ge``), and full name
        (``Genesis``).

        Args:
            name: A book name or abbreviation (e.g., "Genesis", "Gen",
                  "Ge", "1 Samuel", "1Sam").
            language: ISO 639-3 language code (default ``"eng"``).
                      Currently only affects logging; localization
                      lookups use the name directly.

        Returns:
            The OSIS ID (e.g., ``"Gen"``, ``"Matt"``) or ``None`` if
            the name cannot be resolved.
        """
        try:
            book = self._books.findbook(name)
            return book.osisID  # type: ignore[no-any-return]
        except (ValueError, AssertionError):
            return None

    def get_book_names(self, osis_id: str, language: str = "eng") -> list[str]:
        """Get all known names and abbreviations for a book.

        Args:
            osis_id: OSIS identifier (e.g., ``"Gen"``, ``"Matt"``).
            language: ISO 639-3 code for localized names. When
                      non-English, returns the localized full name
                      and abbreviation from books_<lang>.tsv.

        Returns:
            A list of name strings, or an empty list if the book
            is not found.
        """
        try:
            book = self._books.fromosis(osis_id)
        except (AssertionError, ValueError):
            return []

        names: list[str] = [book.name, book.usfmname, book.osisID, book.biblia]
        if getattr(book, "altname", ""):
            names.append(book.altname)

        # Add localized names if a non-English language is requested
        if language != "eng":
            localized = get_localized_books(language)
            if localized is not None:
                try:
                    names.append(localized.get_name(book.usfmname))
                    names.append(localized.get_abbrev(book.usfmname))
                except (AssertionError, KeyError):
                    pass

        return names

    # ------------------------------------------------------------------
    # Reference validation
    # ------------------------------------------------------------------

    def validate_reference(
        self,
        book: str,
        chapter: int,
        verse: int,
        canon: str = "protestant",
    ) -> bool:
        """Check whether a book/chapter/verse reference is valid.

        Validates that:
          1. The book name resolves to a known OSIS ID.
          2. The chapter exists for that book.
          3. The verse exists within that chapter.

        Uses biblelib's ``unit.chapter.Chapter`` which loads
        versification data from ``chapterverses.tsv``.

        Args:
            book: OSIS ID or book name (e.g., ``"Gen"``, ``"Matt"``).
            chapter: 1-based chapter number.
            verse: 1-based verse number.
            canon: Canon name (``"protestant"`` only currently supported
                   by biblelib's Books class).

        Returns:
            ``True`` if the reference is valid, ``False`` otherwise.
        """
        try:
            from biblelib.word import BCID  # noqa: F811

            # Resolve the book to its USFM number
            book_inst = self._books.fromosis(book)
            usfm_num = book_inst.usfmnumber  # e.g. "01" for Genesis

            # Build chapter ID (BBCCC format) and check bounds
            chap_id = f"{usfm_num}{chapter:03d}"
            from biblelib.unit.chapter import Chapter  # noqa: F811

            chap = Chapter(inst=BCID(chap_id))
            return 1 <= verse <= chap.lastverse
        except Exception:
            return False


def biblelib_available() -> bool:
    """Return ``True`` if the biblelib package is installed and importable."""
    return _BIBLELIB_AVAILABLE
