"""Stable tenant bucketing. Invalid or unavailable config keeps old behavior."""
import hashlib
import hmac
import json


def enabled(tenant_id, experiment, percent, secret_key):
    if (not isinstance(tenant_id, str) or not tenant_id or
            not isinstance(experiment, str) or not experiment or
            type(percent) is not int or not 0 <= percent <= 100 or
            not isinstance(secret_key, bytes) or len(secret_key) < 32):
        return False
    payload = json.dumps([experiment, tenant_id], ensure_ascii=False, separators=(',', ':')).encode()
    bucket = int.from_bytes(hmac.new(secret_key, payload, hashlib.sha256).digest()[:8], 'big') % 10000
    return bucket < percent * 100
