# MCard package initialization
from importlib.metadata import PackageNotFoundError, version

try:
    __version__ = version("mcard")
except PackageNotFoundError:
    __version__ = "0.1.49"  # fallback to pyproject.toml version

import os

from . import file_io, loader
from .config.config_constants import DEFAULT_DB_PATH
from .config.env_parameters import EnvParameters
from .config.logging import get_logger, setup_logging
from .engine.sqlite_engine import SQLiteConnection, SQLiteEngine
from .model.card import MCard
from .model.card_collection import CardCollection

# Note: Do not initialize logging on import. Entry points should call
# mcard.config.logging.setup_logging() explicitly.

# Define the most commonly used classes in __all__
__all__ = [
    "MCard",
    "CardCollection",
    "SQLiteConnection",
    "SQLiteEngine",
    "EnvParameters",
    "file_io",
    "loader",
    "setup_logging",
    "get_logger",
    "default_collection",
]

# Lazy default_collection: avoid opening a SQLite connection on bare `import mcard`
_default_collection = None


def get_default_collection():
    """Get or create the default CardCollection (lazy initialization)."""
    global _default_collection
    if _default_collection is None:
        db_path = os.environ.get("MCARD_DB_PATH")
        if not db_path:
            os.makedirs(os.path.dirname(DEFAULT_DB_PATH), exist_ok=True)
            db_path = DEFAULT_DB_PATH
        _default_collection = CardCollection(db_path=db_path)
    return _default_collection


def __getattr__(name):
    if name == "default_collection":
        return get_default_collection()
    raise AttributeError(f"module 'mcard' has no attribute {name!r}")
