import json
import uuid
import logging
import time
from MediaSpiders.utils.string_utils import get_str_md5


def parse_weibo_response(rsp_str):
    rsp_body = json.loads(rsp_str)
    result_array = []
    if rsp_body['ok'] == 1:
        realtime_data = rsp_body['data']['realtime']
        current_timestamp = int(time.time()) * 1000
        for line in realtime_data:
            try:
                custom_sid = str(uuid.uuid4())
                result_line = {
                    "id": custom_sid,
                    "hot_id": get_str_md5(line['word']),
                    "hot_word": line['word'],
                    "hot_value": line['num'],
                    "category": "",
                    "realtime_rank": line['rank'],
                    "platform": "微博",
                    "onboard_time": current_timestamp,
                    "crawl_time": current_timestamp,
                    "fake_url": f"https://weibo.com/ajax/side/hotSearch/{custom_sid}"
                }
                if 'flag_desc' in line:
                    result_line['category'] = line['flag_desc']
                result_array.append(result_line)
            except Exception as e:
                logging.error(f"解析错误：{repr(e)}")
                logging.info(json.dumps(line, ensure_ascii=False))
    return result_array


def parse_toutiao_response(rsp_str):
    rsp_body = json.loads(rsp_str)
    result_array = []
    if rsp_body['status'] == "success":
        realtime_data = rsp_body['data']
        current_timestamp = int(time.time()) * 1000
        rank = 0
        for line in realtime_data:
            rank += 1
            try:
                custom_sid = str(uuid.uuid4())
                result_line = {
                    "id": custom_sid,
                    "hot_id": line['ClusterIdStr'],
                    "hot_word": line['Title'],
                    "hot_value": int(line['HotValue']),
                    "category": "",
                    "realtime_rank": rank,
                    "platform": "今日头条",
                    "onboard_time": current_timestamp,
                    "crawl_time": current_timestamp,
                    "fake_url": f"https://www.toutiao.com/hot-event/hot-board/{custom_sid}"
                }
                if 'InterestCategory' in line:
                    result_line['category'] = ",".join(line['InterestCategory'])
                result_array.append(result_line)
            except Exception as e:
                logging.error(f"解析错误：{repr(e)}")
                logging.info(json.dumps(line, ensure_ascii=False))
    return result_array


if __name__ == "__main__":
    # rsp_file = open("./toutiao_hot_search.json", 'r', encoding='utf-8')
    rsp_file = open("./weibo_hot_search.json", 'r', encoding='utf-8')
    read_str = rsp_file.read()
    rsp_file.close()
    # result_arr = parse_toutiao_response(read_str)
    result_arr = parse_weibo_response(read_str)
    pass
