import json
import os
import traceback

import faiss
import numpy as np
from gm_rpcd.all import bind
from utils.cache import redis_client_db
from utils.message import send_msg_to_dingtalk
from utils.personas import get_user_portrait_tag3_from_redis

MODEL_PATH = os.path.join(os.getcwd(), "_models")
INDEX_PATH = os.path.join(MODEL_PATH, "faiss_personas_vector.index")
FAISS_TAGS_INDEX = faiss.read_index(INDEX_PATH)

TAG_EMBEDDING_DICT = redis_client_db.hgetall("personas_tags_embedding")


@bind("strategy_embedding/personas_vector/match")
def match_tractate_by_device(device_id, n=10):
    try:
        business_tags = get_user_portrait_tag3_from_redis(device_id, tags_num=5).get("business_tags", [])
        # business_tags = ["假体下巴", "你好", "假体隆胸"]
        res = []
        vectors = []
        for tag in business_tags:
            lst = json.loads(TAG_EMBEDDING_DICT.get(bytes(tag, "utf-8"), b"[]"))
            if lst:
                vectors.append(np.array(lst).astype("float32"))
        if vectors:
            D, I = FAISS_TAGS_INDEX.search(np.array([np.average(vectors, axis=0)]).astype("float32"), n)
            res = I.tolist()[0]
        return res
    except Exception as e:
        send_msg_to_dingtalk(str(traceback.format_exc()))
        return []
