import json
from pathlib import Path
from typing import Any, Dict, Optional


DEFAULT_CONFIG_PATH = Path(__file__).resolve().parent.parent / "config.json"


def load_config(defaults: Optional[Dict[str, Any]] = None,
                config_file: Optional[str] = None) -> Dict[str, Any]:
    """Load JSON configuration with defaults and error handling.

    Parameters
    ----------
    defaults: Optional[Dict[str, Any]]
        Default values returned when the config file is missing or invalid.
    config_file: Optional[str]
        Path to the config file. If not provided, ``config.json`` in the
        repository root is used.

    Returns
    -------
    Dict[str, Any]
        Parsed configuration merged with the provided defaults.
    """
    defaults = defaults or {}
    path = Path(config_file) if config_file else DEFAULT_CONFIG_PATH
    try:
        with path.open("r", encoding="utf-8") as fh:
            data = json.load(fh)
        if not isinstance(data, dict):
            raise ValueError("Config is not a JSON object")
    except Exception:
        data = {}
    result = defaults.copy()
    result.update(data)
    return result


__all__ = ["load_config"]
