import re
from typing import Dict, List, Callable
import ai_utils
import spider_api
import asr_utils
import tos_utlis
import json

from ai_chat_stream import sys_content


def parse_url(link: str) -> Dict:
    if "douyin" in link:
        return {"platform": "dy", "type": "video", "url": link}
    elif "xiaohongshu" in link or "xhslink" in link:
        return {"platform": "xhs", "type": "video", "url": link}
    elif "bilibili" in link:
        return {"platform": "bili", "type": "video", "url": link}
    elif "kuaishou" in link:
        return {"platform": "ks", "type": "video", "url": link}
    else:
        return {"platform": "unknown", "type": "unknown", "url": link}


############################################################
# 抖音
def process_douyin_video(url: str, data: Dict):
    try:
        data = spider_api.get_dy_ocr_info(url)

        if data is None or len(data) < 3:  # 先判断是否为None，再判断长度
            res_data = create_res_data("链接有误", 1)
            yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
            return

        else:
            if data.get('aweme_type') == 68:

                spider_data = {
                    "aweme_type": "TUWEN",
                    "collect_count": str(data.get('collect_count')),
                    "comment_count": str(data.get('comment_count')),
                    "cover": f'https://static2.douchacha.com/assets/{data.get("video_id")}/0.jpg',
                    "create_time": str(data.get('create_time')),
                    "digg_count": str(data.get('digg_count')),
                    "download_count": str(data.get('download_count')),
                    "download_images": get_dy_download_images(int(data.get("video_id")), data.get("image_length")),
                    "download_video_url": str(data.get("download_video_url")),
                    "duration": str(data.get("duration")),
                    "image_length": str(data.get("image_length")),
                    "item_title": str(data.get("item_title")),
                    "recommend_count": str(data.get("recommend_count")),
                    "share_count": str(data.get("share_count")),
                    "title": str(data.get("title")),
                    "video_id": str(data.get("video_id")),
                    "url": url,
                    "platform": "DY"
                }

                res_data = create_res_data(spider_data, 5)
                yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')

                sys_list = [{"role": "system", "content": sys_content.comment_content}]
                comment = comment_process(data.get("comments"))
                bot_result_list = ai_utils.get_ai_chat_history_stream_comment(sys_list + convert_dialog_format(comment),
                                                                              type="disabled")
                if bot_result_list:
                    for result in bot_result_list:
                        yield result

            else:
                spider_data = {
                    "aweme_type": "SHIPIN",
                    "collect_count": str(data.get('collect_count')),
                    "comment_count": str(data.get('comment_count')),
                    "cover": f'https://static2.douchacha.com/assets/{data.get("video_id")}/cover.jpg',
                    "create_time": str(data.get('create_time')),
                    "digg_count": str(data.get('digg_count')),
                    "download_count": str(data.get('download_count')),
                    "download_images": str(data.get("download_images")),
                    "download_video_url": str(data.get("download_video_url")),
                    "duration": str(data.get("duration")),
                    "image_length": str(data.get("image_length")),
                    "item_title": str(data.get("item_title")),
                    "recommend_count": str(data.get("recommend_count")),
                    "share_count": str(data.get("share_count")),
                    "title": str(data.get("title")),
                    "video_id": str(data.get("video_id")),
                    "url": url,
                    "platform": "DY"
                }
                res_data = create_res_data(spider_data, 5)
                yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')

                sys_list = [{"role": "system", "content": sys_content.comment_content}]
                comment = comment_process(data.get("comments"))
                bot_result_list = ai_utils.get_ai_chat_history_stream_comment(sys_list + convert_dialog_format(comment),
                                                                              type="disabled")
                if bot_result_list:
                    for result in bot_result_list:
                        yield result

                else:
                    res_data = create_res_data("视频评论获取失败", 0)
                    yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
                    return
    except Exception as e:
        error_data = create_res_data(f"处理失败: {str(e)}", 0)
        yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n".encode('utf-8')


############################################################
# 小红书
def process_xhs_video(url: str, data: Dict):
    try:
        data = spider_api.get_xhs_info(url)
        if data is None or len(data) < 3:  # 先判断是否为None，再判断长度
            res_data = create_res_data("链接有误", 1)
            yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
            return

        else:
            if data.get('type') == 'video':
                spider_data = {
                    "aweme_type": "SHIPIN",
                    "collect_count": str(data.get('collected_count')),
                    "title": str(data.get("desc")),
                    "item_title": str(data.get("desc")),
                    "duration": str(data.get("duration")),
                    "create_time": str(data.get('time')),
                    "comment_count": str(data.get('comment_count')),
                    "digg_count": str(data.get('liked_count')),
                    "image_length": str(data.get("image_length")),
                    "share_count": str(data.get("share_count")),
                    "video_id": str(data.get("note_id")),
                    # 需要爬虫增加的字段
                    "cover": f"https://static2.douchacha.com/xhs/{data.get('note_id')}/cover.jpg",
                    "download_count": data.get('download_count', ''),
                    "download_images": data.get("download_images", []),
                    "download_video_url": data.get("download_video_url", ''),
                    "recommend_count": data.get("recommend_count", ''),
                    "url": url,
                    "platform": "XHS"

                }

                res_data = create_res_data(spider_data, 5)
                yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')

                sys_list = [{"role": "system", "content": sys_content.comment_content}]
                comment = comment_process(data.get("comments"))
                bot_result_list = ai_utils.get_ai_chat_history_stream_comment(sys_list + convert_dialog_format(comment),
                                                                              type="disabled")
                if bot_result_list:
                    for result in bot_result_list:
                        yield result

            else:
                spider_data = {
                    "aweme_type": "TUWEN",
                    "collect_count": str(data.get('collected_count')),
                    "title": str(data.get("desc")),
                    "item_title": str(data.get("desc")),
                    "duration": str(data.get("duration")),
                    "create_time": str(data.get('time')),
                    "comment_count": str(data.get('comment_count')),
                    "digg_count": str(data.get('liked_count')),
                    "image_length": str(data.get("image_length")),
                    "share_count": str(data.get("share_count")),
                    "video_id": str(data.get("note_id")),
                    # 需要爬虫增加的字段
                    "cover": f"https://static2.douchacha.com/xhs/{data.get('note_id')}/0.jpg",
                    "download_count": data.get('download_count', ''),
                    "download_images": get_xhs_download_images(f"{data.get('note_id')}",
                                                               data.get("image_length")),
                    "download_video_url": data.get("download_video_url", ''),
                    "recommend_count": data.get("recommend_count", ''),
                    "url": url,
                    "platform": "XHS"

                }

                res_data = create_res_data(spider_data, 5)
                yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')

                sys_list = [{"role": "system", "content": sys_content.comment_content}]
                comment = comment_process(data.get("comments"))
                bot_result_list = ai_utils.get_ai_chat_history_stream_comment(sys_list + convert_dialog_format(comment),
                                                                              type="disabled")
                if bot_result_list:
                    for result in bot_result_list:
                        yield result

    except Exception as e:
        # error_data = create_res_data(f"处理失败: {str(e)}", 0)
        error_data = create_res_data(f"暂不支持", 1)
        yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n".encode('utf-8')


############################################################
# 快手
def process_ks_video(url: str, data: Dict):
    try:
        data = spider_api.get_ks_info(url)
        if data is None or len(data) < 3:  # 先判断是否为None，再判断长度
            res_data = create_res_data("链接有误", 1)
            yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
            return

        spider_data = {
            "aweme_type": "SHIPIN",
            "title": str(data.get("caption")),
            "item_title": str(data.get("caption")),
            "cover": f"https://static2.douchacha.com/ks/{data.get('video_id')}/cover.jpg",
            "duration": str(data.get("duration")),
            "digg_count": str(data.get('like_count')),
            "video_id": str(data.get("video_id")),
            # 需要爬虫增加的字段
            "create_time": str(data.get('time', '')),
            "comment_count": str(data.get('comment_count', '')),
            "image_length": str(data.get("image_length", '')),
            "share_count": str(data.get("share_count", '')),
            "collect_count": str(data.get('collected_count', '')),
            "download_count": str(data.get('download_count', '')),
            "download_images": str(data.get("download_images", [])),
            "download_video_url": str(data.get("download_video_url", '')),
            "recommend_count": str(data.get("recommend_count", '')),
            "url": url,
            "platform": "KS"

        }

        res_data = create_res_data(spider_data, 5)
        yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')

        sys_list = [{"role": "system", "content": sys_content.comment_content}]
        comment = comment_process(data.get("comments"))
        bot_result_list = ai_utils.get_ai_chat_history_stream_comment(sys_list + convert_dialog_format(comment),
                                                                      type="disabled")
        if bot_result_list:
            for result in bot_result_list:
                yield result


    except Exception as e:
        error_data = create_res_data(f"处理失败: {str(e)}", 0)
        yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n".encode('utf-8')


############################################################
# B站
def process_bzhan_video(url: str, data: Dict):
    try:
        data = spider_api.get_bilibili_info(url)

        if data is None or len(data) < 3:  # 先判断是否为None，再判断长度
            res_data = create_res_data("链接有误", 1)
            yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
            return

        spider_data = {
            "aweme_type": "SHIPIN",
            "title": str(data.get("title")),
            "item_title": str(data.get("title")),
            "cover": f"https://static2.douchacha.com/bilibili/{data.get('bvid')}/cover.jpg",
            "duration": str(data.get("duration")*1000),
            "digg_count": str(data.get('like_count')),
            "video_id": str(data.get("like")),
            # 需要爬虫增加的字段
            "create_time": str(data.get('pubdate', '')),
            "comment_count": str(data.get('comment_count', '')),
            "image_length": str(data.get("image_length", '')),
            "share_count": str(data.get("share", '')),
            "collect_count": str(data.get('collected_count', '')),
            "download_count": str(data.get('download_count', '')),
            "download_images": str(data.get("download_images", [])),
            "download_video_url": str(data.get("download_video_url", '')),
            "recommend_count": str(data.get("reply", '')),
            "platform": "BL",
            "url": url,

        }

        res_data = create_res_data(spider_data, 5)
        yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')

        sys_list = [{"role": "system", "content": sys_content.comment_content}]
        comment = comment_process(data.get("comments"))
        bot_result_list = ai_utils.get_ai_chat_history_stream_comment(sys_list + convert_dialog_format(comment),
                                                                      type="disabled")
        if bot_result_list:
            for result in bot_result_list:
                yield result

    except Exception as e:
        error_data = create_res_data(f"处理失败: {str(e)}", 0)
        yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n".encode('utf-8')


############################################################

def process_urls(urls: List[str]):
    try:
        url = urls[-1]
        parsed_data = parse_url(url)
        platform = parsed_data["platform"]
        content_type = parsed_data["type"]

        if platform == "dy" and content_type == "video":
            yield from process_douyin_video(url, parsed_data)
        elif platform == "xhs" and content_type == "video":
            yield from process_xhs_video(url, parsed_data)
        elif platform == "bili" and content_type == "video":
            yield from process_bzhan_video(url, parsed_data)
        elif platform == "ks" and content_type == "video":
            yield from process_ks_video(url, parsed_data)
    except Exception as e:
        error_data = create_res_data(f"请提供视频或者图文链接", 1)
        yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n".encode('utf-8')


def extract_comment_to_text(text: str):
    url_pattern = re.compile(r'https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]')
    urls = url_pattern.findall(text)
    yield from process_urls(urls)


def convert_dialog_format(original_dialog: list) -> list:
    converted = []
    for item in original_dialog:
        if 'user' in item:
            converted.append({
                'role': 'user',
                'content': item['user']
            })
        elif 'assistant' in item:
            converted.append({
                'role': 'assistant',
                'content': item['assistant']
            })
        else:
            continue
    return converted


def get_last_user_value(dialogs: list) -> str or None:
    last_user_content = None
    for item in dialogs:
        if 'user' in item:
            last_user_content = item['user']
    if last_user_content is not None:
        return [{'role': 'user', 'content': last_user_content}]
    return None


def transform_image_urls(url_list: List[str]) -> List[Dict]:
    return [
        {
            "type": "image_url",
            "image_url": {"url": url}
        }
        for url in url_list
    ]


def create_res_data(message, type_):
    return {
        "message": message,
        "type": type_
    }


def get_dy_download_images(video_id, image_length):
    download_images = []
    for i in range(image_length):
        download_images.append({
            "image_index": i,
            "image_url": f"https://static2.douchacha.com/assets/{video_id}/{i}.jpg"
        })
    return download_images


def get_xhs_download_images(video_id, image_length):
    download_images = []
    for i in range(image_length):
        download_images.append({
            "image_index": i,
            "image_url": f"https://static2.douchacha.com/xhs/{video_id}/{i}.jpg"
        })
    return download_images


def comment_process(comments):
    commenr_list = []
    for comm in comments:
        commenr_list.append(comm.get('text'))
    comment = [
        {
            "user": ", ".join(commenr_list)
        }
    ]
    return comment
