import json

from utils.cache import redis_client2


def get_user_portrait_tag3_redis_key(device_id):
    return "doris:user_portrait:tag3:device_id:" + str(device_id)


def items_gt_score(d, limit_score=0, tags_num=5):
    new_d = dict(sorted(d.items(), key=lambda x: x[1], reverse=True))
    res = []
    count = 0
    for (tag, score) in new_d.items():
        if float(score) >= limit_score and count < tags_num:
            res.append(tag)
            count += 1
    return res


def get_user_portrait_tag3_from_redis(device_id, limit_score=0, tags_num=5):
    portrait_key = get_user_portrait_tag3_redis_key(device_id)
    if redis_client2.exists(portrait_key):
        user_portrait = json.loads(redis_client2.get(portrait_key))
        first_demands = items_gt_score(user_portrait.get("first_demands", {}), limit_score=limit_score, tags_num=tags_num)
        second_demands = items_gt_score(user_portrait.get("second_demands", {}), limit_score=limit_score, tags_num=tags_num)
        first_solutions = items_gt_score(user_portrait.get("first_solutions", {}), limit_score=limit_score, tags_num=tags_num)
        second_solutions = items_gt_score(user_portrait.get("second_solutions", {}), limit_score=limit_score, tags_num=tags_num)
        first_positions = items_gt_score(user_portrait.get("first_positions", {}), limit_score=limit_score, tags_num=tags_num)
        second_positions = items_gt_score(user_portrait.get("second_positions", {}), limit_score=limit_score, tags_num=tags_num)
        projects = items_gt_score(user_portrait.get("projects", {}), limit_score=limit_score, tags_num=tags_num)
        anecdote_tags = items_gt_score(user_portrait.get("anecdote_tags", {}), limit_score=limit_score, tags_num=tags_num)
        business_tags = items_gt_score(user_portrait.get("business_tags", {}), limit_score=limit_score, tags_num=tags_num)
        return {
            "first_demands": first_demands,
            "second_demands": second_demands,
            "first_solutions": first_solutions,
            "second_solutions": second_solutions,
            "first_positions": first_positions,
            "second_positions": second_positions,
            "projects": projects,
            "anecdote_tags": anecdote_tags,
            "business_tags": business_tags
        }
    return {}


def get_user_portrait_tag3_business_tags(device_id, limit_score=0, tags_num=5):
    portrait_key = get_user_portrait_tag3_redis_key(device_id)
    if redis_client2.exists(portrait_key):
        user_portrait = json.loads(redis_client2.get(portrait_key))
        business_tags = items_gt_score(user_portrait.get("business_tags", {}), limit_score=limit_score, tags_num=tags_num)
        return business_tags
    return []
