import datetime
import traceback
from my_config import set_config
from log import Log
from my_utils import request_post, RedisHelper

config_, _ = set_config()
log_ = Log()
redis_helper = RedisHelper()


def get_limit_videos(now_date):
    """获取限流视频并存入redis"""
    # 通过接口获取需要限流的视频
    data = request_post(request_url=config_.GET_VIDEO_LIMIT_LIST_URL)
    if data is None:
        return
    limit_data = data.get('data', [])
    log_.info(f"limit_data = {limit_data}")
    video_limit_list = []  # [(videoId, maxDistributeCount), ...]
    video_id_list = []
    for item in limit_data:
        video_id = int(item['videoId'])
        max_distribute_count = int(item['maxDistributeCount'])
        video_id_list.append(video_id)
        video_limit_list.append((video_id, max_distribute_count))
    if len(video_limit_list) == 0:
        return
    # 视频对应最大分发数 存入redis
    redis_helper.set_data_to_redis(key_name=config_.KEY_NAME_PREFIX_LIMIT_VIDEOS, value=str(video_limit_list))
    # 限流视频videoId 存入当日redis key
    redis_helper.add_data_with_set(
        key_name=f"{config_.KEY_NAME_PREFIX_LIMIT_VIDEO_SET}{datetime.datetime.strftime(now_date, '%Y%m%d')}",
        values=tuple(video_id_list),
        expire_time=24*3600
    )


def del_yesterday_limit_videos_record(now_date):
    """清除前一天的视频分发数记录"""
    dt = datetime.datetime.strftime(now_date - datetime.timedelta(days=1), '%Y%m%d')
    # 获取前一天限流视频
    video_list = redis_helper.get_data_from_set(key_name=f"{config_.KEY_NAME_PREFIX_LIMIT_VIDEO_SET}{dt}")
    if video_list is None:
        return
    for video_id in video_list:
        redis_helper.del_keys(key_name=f"{config_.KEY_NAME_PREFIX_LIMIT_VIDEO_DISTRIBUTE_COUNT}{video_id}")


if __name__ == '__main__':
    try:
        now_date = datetime.datetime.today()
        now_h = datetime.datetime.now().hour
        log_.info(f"now_date = {now_date}, now_h = {now_h}")
        if now_h == 0:
            # 0点清除前一天限流视频分发记录
            del_yesterday_limit_videos_record(now_date=now_date)
            log_.info("成功清除前一天限流视频分发记录！")
        # 获取最新限流视频
        get_limit_videos(now_date=now_date)
        log_.info("成功获取最新限流视频！")
    except Exception as e:
        log_.error("限流视频更新失败！")
        log_.error(traceback.format_exc())
