import hashlib
import random
from apps.featureflags.models import FeatureFlag, UserFeatureFlag


def _hash_percentage(key: str) -> int:
    # deterministic hash to 0-99
    h = hashlib.sha256(key.encode('utf-8')).hexdigest()
    return int(h[:8], 16) % 100


def is_feature_enabled(flag_name: str, user=None) -> bool:
    # check user override
    try:
        flag = FeatureFlag.objects.filter(name=flag_name).first()
    except Exception:
        return False

    if user is not None:
        try:
            uo = UserFeatureFlag.objects.filter(feature_flag=flag, user=user).first()
            if uo is not None:
                return bool(uo.is_enabled)
        except Exception:
            pass

    if not flag:
        return False

    if flag.is_enabled and flag.rollout_percentage <= 0:
        return True

    if flag.rollout_percentage > 0 and user is not None:
        # use deterministic hash of user id + flag name
        key = f"{user.id}:{flag_name}"
        pct = _hash_percentage(key)
        return pct < int(flag.rollout_percentage)

    return bool(flag.is_enabled)
