# recharge/services/goterpay_client.py
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .goterpay_api import GoterPayAPI, GoterPayConfig


def _get(cfg: dict, *keys, default=None):
    """Fetch first present key (case-insensitive) from cfg."""
    for k in keys:
        if k in cfg:
            return cfg[k]
        # try case variants
        if k.lower() in cfg:
            return cfg[k.lower()]
        if k.upper() in cfg:
            return cfg[k.upper()]
    return default


def get_goterpay_client() -> GoterPayAPI:
    provider = getattr(settings, "RECHARGE_PROVIDER", None)
    if not provider:
        raise ImproperlyConfigured("RECHARGE_PROVIDER is not set in settings.")

    providers = getattr(settings, "RECHARGE_PROVIDERS", {})
    cfg = providers.get(provider)
    if not cfg:
        raise ImproperlyConfigured(f"RECHARGE_PROVIDERS has no config for provider '{provider}'.")

    if provider != "goterpay":
        raise ImproperlyConfigured(
            f"get_goterpay_client() called but RECHARGE_PROVIDER='{provider}'. "
            f"Set RECHARGE_PROVIDER='goterpay' or use the appropriate client factory."
        )

    mid = _get(cfg, "mid", "MID")
    mkey = _get(cfg, "mkey", "MKEY")
    subwallet = _get(cfg, "subwallet", "SUBWALLET")
    timeout = _get(cfg, "timeout", "TIMEOUT", default=20)

    missing = [name for name, val in (("mid", mid), ("mkey", mkey)) if not val]
    if missing:
        raise ImproperlyConfigured(
            f"Missing required GoterPay config keys in RECHARGE_PROVIDERS['goterpay']: {', '.join(missing)}"
        )

    return GoterPayAPI(
        GoterPayConfig(
            mid=mid,
            mkey=mkey,
            subwallet=subwallet,
            timeout=int(timeout) if timeout is not None else 20,
        )
    )


# from django.conf import settings
# from .goterpay_api import GoterPayAPI, GoterPayConfig

# def get_goterpay_client() -> GoterPayAPI:
#     cfg = settings.GOTERPAY
#     return GoterPayAPI(GoterPayConfig(
#         mid=cfg["MID"],
#         mkey=cfg["MKEY"],
#         subwallet=cfg.get("SUBWALLET"),
#         timeout=cfg.get("TIMEOUT", 20),
#     ))
