import importlib
from typing import Any

def _import_module(key: str):
    """
    Try to import as a submodule of this package first (e.g. description.mildew),
    then fall back to bare name.
    """
    pkg = __package__
    if pkg:
        try:
            return importlib.import_module(f"{pkg}.{key}")
        except ImportError:
            pass
    return importlib.import_module(key)  # fallback

def fetch(dataset: str, *args, **kwargs) -> Any:
    key = dataset.lower()
    try:
        module = _import_module(key)
    except ImportError as e:
        raise ImportError(f"Could not import module for dataset '{dataset}': {e}") from e

    func_name = f"fetch_{key}"
    if not hasattr(module, func_name):
        raise AttributeError(f"Module '{module.__name__}' has no function '{func_name}'")
    return getattr(module, func_name)(*args, **kwargs)


def get_metadata(dataset: str) -> dict[str, Any]:
    key = dataset.lower()
    try:
        module = _import_module(key)
    except ImportError as e:
        raise ImportError(f"Could not import module for dataset '{dataset}': {e}") from e

    return {
        'variable_description': getattr(module, f"variable_description_{key}", None),
        'dataset_description': getattr(module, f"dataset_description_{key}", None),
    }


def fetch_with_metadata(dataset: str, *args, **kwargs) -> dict[str, Any]:
    data = fetch(dataset, *args, **kwargs)
    meta = get_metadata(dataset)
    return {'data': data, **meta}
