"""
b64t - High-performance base64 encoding/decoding

This package requires the system b64t package to be installed:
    apt install b64t
"""

import sys
from pathlib import Path

# Paths where the system extension might be installed
SYSTEM_EXTENSION_PATHS = [
    "/usr/lib/python3/dist-packages/b64t.abi3.so",
    "/usr/local/lib/python3/dist-packages/b64t.abi3.so",
]


def _find_system_extension():
    """Find the system-installed b64t extension."""
    for path in SYSTEM_EXTENSION_PATHS:
        if Path(path).exists():
            return path
    return None


# Verify system installation exists
_system_ext = _find_system_extension()
if _system_ext is None:
    raise ImportError(
        "b64t system extension not found.\n"
        "\n"
        "This pip package requires the system b64t package:\n"
        "    apt install b64t\n"
        "\n"
        "Install the system package first, then use pip in a virtual environment."
    )

# Add system dist-packages to path if not already present
_system_dist_packages = "/usr/lib/python3/dist-packages"
if _system_dist_packages not in sys.path:
    sys.path.insert(0, _system_dist_packages)

# Import from the system extension
# The .pth file should have added dist-packages to sys.path
try:
    # Import the C extension module
    # The module exports PyInit_b64t, so we must use "b64t" as the module name
    import importlib.util
    spec = importlib.util.spec_from_file_location("b64t", _system_ext)
    _b64t = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(_b64t)

    # Re-export all public symbols
    encode = _b64t.encode
    decode = _b64t.decode
    encodePipe = _b64t.encodePipe
    decodePipe = _b64t.decodePipe
    B64TError = _b64t.B64TError
    EncodingError = _b64t.EncodingError
    DecodingError = _b64t.DecodingError
    __version__ = getattr(_b64t, "__version__", "0.1.0")

except Exception as e:
    raise ImportError(
        f"Failed to import system b64t extension from {_system_ext}\n"
        f"Error: {e}\n"
        "\n"
        "Verify the system package is installed correctly:\n"
        "    apt install --reinstall b64t\n"
    ) from e
