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

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

import sys
from pathlib import Path

# Paths where the system extension might be installed
SYSTEM_EXTENSION_PATHS = [
    # Linux (APT)
    "/usr/lib/python3/dist-packages/b64t.abi3.so",
    "/usr/local/lib/python3/dist-packages/b64t.abi3.so",
    # macOS Homebrew ARM64 (Apple Silicon)
    "/opt/homebrew/lib/python3/dist-packages/b64t.abi3.so",
    # macOS Homebrew Intel (shares path with Linux /usr/local)
]


def _get_install_command():
    """Get the appropriate install command for the current platform."""
    if sys.platform == "darwin":
        return "brew install b64t"
    return "apt install b64t"


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:
    _install_cmd = _get_install_command()
    raise ImportError(
        "b64t system extension not found.\n"
        "\n"
        "This pip package requires the system b64t package:\n"
        f"    {_install_cmd}\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_paths = [
    "/usr/lib/python3/dist-packages",          # Linux (APT)
    "/opt/homebrew/lib/python3/dist-packages",  # macOS Homebrew ARM64
    "/usr/local/lib/python3/dist-packages",     # macOS Homebrew Intel / Linux local
]
for _path in _system_dist_packages_paths:
    if _path not in sys.path:
        sys.path.insert(0, _path)

# 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:
    _reinstall_cmd = _get_install_command()
    if sys.platform != "darwin":
        _reinstall_cmd += " --reinstall"
    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"
        f"    {_reinstall_cmd}\n"
    ) from e
