package com.tzld.piaoquan.ad.engine.commons.util;

import com.tzld.piaoquan.ad.engine.commons.helper.NewExpHelper;
import org.apache.commons.collections4.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

public class AbUtil {

    public static final List<String> adAlgExpCode = Arrays.asList("679", "680", "683", "687", "688", "833", "834", "840", "843", "847", "849", "851", "865", "872", "894", "901", "902");

    public static Set<String> unfoldAllExpCode(List<Map<String, String>> adAbMap) {
        if (CollectionUtils.isEmpty(adAbMap)) {
            return new HashSet<>();
        }
        return adAbMap.stream()
                .map(m -> m.get("abExpCode"))
                .filter(Objects::nonNull)
                .map(Object::toString)
                .collect(Collectors.toSet());
    }

    /**
     * 判断用户是否在某个实验中，包含在新实验系统和旧实验系统
     */
    public static boolean isInAbExp(Collection<String> expCodeSet, Object appType, int newExpGroup, String expCode) {
        if (CollectionUtils.isEmpty(expCodeSet)) {
            return false;
        }
        if (expCodeSet.contains(expCode)) {
            return true;
        }

        if (expCodeSet.contains(NewExpHelper.flagId)) {
            return NewExpHelper.checkInNewExpGroup(appType.toString(), newExpGroup, expCode);
        }
        return false;
    }

    public static String chooseAdAlgExpCode(Set<String> expCodeSet, Object appType, int newExpGroup) {
        for (String expCode : adAlgExpCode) {
            if (AbUtil.isInAbExp(expCodeSet, appType, newExpGroup, expCode)) {
                return expCode;
            }
        }
        return "";
    }

    /**
     * ad-engine 尾号实验固定用「广告算法实验」层 = rootSessionId 倒数第6位(index 5)。
     * 只认这一层,防止别的位的实验被 ID 误命中。
     * ponytail: 固定常量;若要不停机切层,改成 Apollo 注入到调用处。
     */
    public static final int ENGINE_TAIL_INDEX = 5;

    /**
     * 展开尾号实验命中列表,只保留生效位(tailIndex)== wantIndex 的实验编号。
     * tailIndex 透传过来可能是数字也可能是字符串,统一转字符串比较。
     */
    public static Set<String> unfoldTailExpCode(List<Map<String, Object>> tailArr, int wantIndex) {
        if (CollectionUtils.isEmpty(tailArr)) {
            return new HashSet<>();
        }
        return tailArr.stream()
                .filter(m -> Objects.equals(String.valueOf(wantIndex), String.valueOf(m.get("tailIndex"))))
                .map(m -> m.get("abExpCode"))
                .filter(Objects::nonNull)
                .map(Object::toString)
                .collect(Collectors.toSet());
    }

    /**
     * 尾号实验命中判断：与 AB 来源隔离，直接按实验编号匹配，不走新实验分组逻辑
     */
    public static boolean isInTailExp(Collection<String> tailExpCodeSet, String expCode) {
        return CollectionUtils.isNotEmpty(tailExpCodeSet) && tailExpCodeSet.contains(expCode);
    }
}
