import os
import json
import random
import sys
import time
import uuid

import requests

sys.path.append(os.getcwd())
from common.video_item import VideoItem
from common import tunnel_proxies
from common.pipeline import PiaoQuanPipelineTest


class YiQiFengFaRecommend(object):
    def __init__(self, platform, mode, rule_dict, user_list, env):
        self.platform = platform
        self.mode = mode
        self.rule_dict = rule_dict
        self.user_list = user_list
        self.env = env
        self.download_cnt = 0
        self.limit_flag = False

    def get_video_list(self, token):
        """
        推荐流大约110条数据，目前暂时不会更新
        """
        headers = {
            'Host': 'api.xiahong.top',
            'ik': 'b326b5062b2f0e69046810717534cb09',
            'xweb_xhr': '1',
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/6.8.0(0x16080000) NetType/WIFI MiniProgramEnv/Mac MacWechat/WMPF MacWechat/3.8.5(0x13080510)XWEB/1100',
            'token': token,
            'Content-Type': 'application/json',
            'Accept': '*/*',
            'Sec-Fetch-Site': 'cross-site',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Dest': 'empty',
            'Referer': 'https://servicewechat.com/wxe5389a260a0a4ee2/2/page-frame.html',
            'Accept-Language': 'en-US,en;q=0.9',
        }
        while True:
            time.sleep(random.randint(1, 10))
            try:
                if self.limit_flag:
                    message = "本轮已经抓取到足够的数据，自动退出\t{}".format(self.download_cnt)
                    print(message)
                    return
                else:
                    params = {
                        's': 'mobile/Video/getList',
                        'cid': '1',
                        'page': '11',
                        'api_version': '4',
                        'appid': 'wxe5389a260a0a4ee2',
                        'version': '1.9.1',
                        'env_version': 'release',
                        'scene': '1089'
                    }
                    response = requests.get('https://api.xiahong.top/index.php', headers=headers, params=params, proxies=tunnel_proxies())
                    video_list = response.json()['data']['list']
                    if video_list:
                        for index, video_obj in enumerate(video_list, 1):
                            try:
                                print("扫描到一条视频")
                                self.process_video_obj(video_obj)
                            except Exception as e:
                                print("抓取第{}条的时候出现问题， 报错信息是{}".format(index, e))
                    else:
                        print("已经抓完了，自动退出")
                        return
            except Exception as e:
                print("抓取推荐页的时候出现错误， 报错信息是{}".format(e))

    def process_video_obj(self, video_obj):
        obj = {
            "id": 224708,
            "title": "🔴这个女博士的遭遇❗️让人心疼，群友们都看看吧！",
            "images": "http://pic.weitunit.com/ca/a9/caa9007f30a99b6b427e1f3664fe527b.jpg",
            "video_url": "https://api-hl.huoshan.com/hotsoon/item/video/_source/?video_id=v0200fg10000clhclejc77u23q1m9ojg&line=0&app_id=0&vquality=normal&watermark=0&long_video=0&sf=4&ts=1702261882&item_id=7305624354258275638",
            "out_link_id": "",
            "type": 0,
            "share_title": "🔴这个女博士的遭遇❗️让人心疼，群友们都看看吧！",
            "image_breathing": False,
            "video_cover": "https://mmbiz.qpic.cn/sz_mmbiz_png/enW3mhIB3IULz7uuISC8VTFZvc6F86PdUpo9ZAdo0UfyBmFPic6l7zoXpKKWU2Dt0Vf2Q8XV9jKkX63yP20G0CA/640?wx_fmt=png&from=appmsg",
            "end_title": "❤️请帮忙转发各大群里！拜托大家！🙏",
            "end_cover": "https://mmbiz.qpic.cn/sz_mmbiz_png/enW3mhIB3IULz7uuISC8VTFZvc6F86PdCVQYE2xgQ9qyjLL43ib6aQ4EaFdFruicY79WUiapcxQK5a955sqia50KFA/640?wx_fmt=png&from=appmsg",
            "author_nickname": "",
            "author_picture": "",
            "prompt_type": "",
            "display_image": "https://mmbiz.qpic.cn/mmbiz_gif/NlUgcycicAT2CehvYKTx4YCTGSMJ8XFRXIQCwX1q6ibG9TprFAGicHre6aicHxQ1qxW0wzUgW5lmRDQDxPdyJNZxag/0?wx_fmt=gif",
            "share_image": "http://pic.weitunit.com/ca/a9/caa9007f30a99b6b427e1f3664fe527b.jpg?x-oss-process=image/resize,m_fill,w_400,h_320,limit_0/watermark,image_bmV3X3dhdGVybWFyay5wbmc_eC1vc3MtcHJvY2Vzcz1pbWFnZS9yZXNpemUsUF81MA,g_center/watermark,image_dmlld3MucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfNDA,g_sw,x_10,y_10/quality,Q_70",
            "click_jump_path_index": "/pages/index/index?videoId=224708&from=video",
            "share_jump_path_index": "/pages/index/index?videoId=224708&from=video",
            "visited": 8376085,
            "shared": 1159920,
            "share_vid": 224708
        }
        trace_id = self.platform + str(uuid.uuid1())
        our_user = random.choice(self.user_list)
        item = VideoItem()
        item.add_video_info("user_id", our_user["uid"])
        item.add_video_info("user_name", our_user["nick_name"])
        item.add_video_info("video_id", video_obj["id"])
        item.add_video_info("video_title", video_obj["title"])
        item.add_video_info("video_url", video_obj['video_url'])
        item.add_video_info("cover_url", video_obj["video_cover"])
        item.add_video_info("play_cnt", video_obj['visited'])
        item.add_video_info("share_cnt", video_obj['shared'])
        item.add_video_info("out_video_id", video_obj["id"])
        item.add_video_info("platform", self.platform)
        item.add_video_info("strategy", self.mode)
        item.add_video_info("session", "{}-{}".format(self.platform, int(time.time())))
        mq_obj = item.produce_item()
        pipeline = PiaoQuanPipelineTest(
            platform=self.platform,
            mode=self.mode,
            rule_dict=self.rule_dict,
            env=self.env,
            item=mq_obj,
            trace_id=trace_id,
        )
        if pipeline.process_item():
            self.download_cnt += 1
            # self.mq.send_msg(mq_obj)
            print(mq_obj)
            print("成功发送至 ETL")
            if self.download_cnt >= int(
                self.rule_dict.get("videos_cnt", {}).get("min", 200)
            ):
                self.limit_flag = True


if __name__ == '__main__':
    S = YiQiFengFaRecommend(
        platform="zhufuyiqifengfa",
        mode="recommend",
        env="dev",
        rule_dict={},
        user_list=[{'nick_name': "Ivring", 'uid': "1997"}, {'nick_name': "paul", 'uid': "1998"}]
    )
    token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDIyNjIzMjUsIm5iZiI6MTcwMjI2MjMyNSwiZXhwIjoxNzAyMjY5NTI1LCJkYXRhIjp7InVzZXJfaWQiOjIzOTI0Nzc0MH19.LKxtz3OKw4ADlcLwU2sWMB5AJ5__aPNdVGqtRuk1ps4"
    S.get_video_list(token)