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:

                url_list = []
                for i in range(data.get('image_length')):
                    if tos_utlis.check_file_in_tos(f"assets/{data.get('video_id')}/{i}.jpg"):
                        url_list.append({
                            "type": "image_url",
                            "image_url": {
                                "url": f"https://douchacha-web.tos-cn-beijing.volces.com/assets/{data.get('video_id')}/{i}.jpg"}
                        })
                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')

                res_data = create_res_data("图文内容提取中", 3)
                yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')

                url_list.append({"type": "text", "text": "提取图片中的文字仅返回图中文字不要返回"})
                image_text_stream = ai_utils.get_image_to_text_stream(url_list)
                for image_text in image_text_stream:
                    yield image_text

            else:

                buffer_url = f"assets/{data.get('video_id')}/{data.get('video_id')}_text.json"

                if tos_utlis.check_file_in_tos_buff(buffer_url):

                    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')

                    res_data = create_res_data("视频文案提取中", 3)
                    yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')

                    tos_data = tos_utlis.get_string_from_tos(buffer_url).get('text')
                    res_data = create_res_data(tos_data, 1)
                    if len(tos_data) > 0:
                        tos_utlis.put_string_to_tos(buffer_url, {'text': tos_data})

                    has_comments = len(data.get("comments", [])) > 0
                    res_ten = create_res_data(
                        "WRITE,COMMENT" if has_comments else "WRITE",
                        10
                    )

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

                elif not tos_utlis.check_file_in_tos_buff(buffer_url):

                    if data.get("duration") / 1000 / 60 > 20:
                        res_data = create_res_data("该视频时长超出20min暂不支持提取", 1)
                        yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
                        return

                    if tos_utlis.check_file_in_tos(f"assets/{data.get('video_id')}/{data.get('video_id')}.mp4"):

                        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')

                        res_data = create_res_data("视频文案提取中", 3)
                        yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')

                        url = f"https://douchacha-web.tos-cn-beijing.volces.com/assets/{data.get('video_id')}/{data.get('video_id')}.mp4"

                        recognizer = asr_utils.SpeechRecognizer()
                        audio_result = recognizer.recognize_audio(url)

                        res_data = create_res_data("识别完成", 3)
                        yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')

                        if audio_result is None:
                            res_data = create_res_data("语音识别失败", 0)
                            yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
                        else:

                            content = audio_result if len(audio_result) > 0 else "该视频没有文案"
                            res_data = create_res_data(content, 1)

                            if len(audio_result) > 0:
                                tos_utlis.put_string_to_tos(buffer_url, {'text': audio_result})

                            has_comments = len(data.get("comments", [])) > 0
                            res_ten = create_res_data(
                                "WRITE,COMMENT" if has_comments else "WRITE",
                                10
                            )

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

                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')

                buffer_url = f"xhs/{data.get('note_id')}/{data.get('note_id')}_text.json"
                if tos_utlis.check_file_in_tos_buff(buffer_url):
                    tos_data = tos_utlis.get_string_from_tos(buffer_url).get('text')
                    res_data = create_res_data(tos_data, 1)
                    if len(tos_data) > 0:
                        tos_utlis.put_string_to_tos(buffer_url, {'text': tos_data})

                    has_comments = len(data.get("comments", [])) > 0
                    res_ten = create_res_data(
                        "WRITE,COMMENT" if has_comments else "WRITE",
                        10
                    )

                    yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
                    yield f"data: {json.dumps(res_ten, ensure_ascii=False)}\n\n".encode('utf-8')
                elif not tos_utlis.check_file_in_tos_buff(buffer_url):
                    if data.get("duration") / 1000 / 60 > 20:
                        res_data = create_res_data("该视频时长超出20min暂不支持提取", 1)
                        yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
                        return

                    if tos_utlis.check_file_in_tos(
                            f"xhs/{data.get('note_id')}/{data.get('note_id')}.mp4"):
                        url = f"https://douchacha-web.tos-cn-beijing.volces.com/xhs/{data.get('note_id')}/{data.get('note_id')}.mp4"
                        res_data = create_res_data("视频文案提取中", 3)
                        yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
                        recognizer = asr_utils.SpeechRecognizer()
                        audio_result = recognizer.recognize_audio(url)
                        if audio_result is None:
                            res_data = create_res_data("语音识别失败", 0)
                            yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
                        else:

                            content = audio_result if len(audio_result) > 0 else "该视频没有文案"
                            res_data = create_res_data(content, 1)

                            if len(audio_result) > 0:
                                tos_utlis.put_string_to_tos(buffer_url, {'text': audio_result})

                            has_comments = len(data.get("comments", [])) > 0
                            res_ten = create_res_data(
                                "WRITE,COMMENT" if has_comments else "WRITE",
                                10
                            )
                            yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
                            yield f"data: {json.dumps(res_ten, ensure_ascii=False)}\n\n".encode('utf-8')


                else:
                    res_data = create_res_data("视频提取失败请稍后重试", 0)
                    yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
                    return
            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')
                url_list = []
                for i in range(data.get('image_length')):
                    if tos_utlis.check_file_in_tos(f"xhs/{data.get('note_id')}/{i}.jpg"):
                        url_list.append({
                            "type": "image_url",
                            "image_url": {
                                "url": f"https://douchacha-web.tos-cn-beijing.volces.com/xhs/{data.get('note_id')}/{i}.jpg"}
                        })
                res_data = create_res_data("图文内容提取中", 3)
                yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')

                url_list.append({"type": "text", "text": "提取图片中的文字仅返回图中文字"})
                image_text_stream = ai_utils.get_image_to_text_stream(url_list)
                for image_text in image_text_stream:
                    yield image_text
    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:
            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')

        buffer_url = f"ks/{data.get('video_id')}/{data.get('video_id')}_text.json"
        if tos_utlis.check_file_in_tos_buff(buffer_url):
            tos_data = tos_utlis.get_string_from_tos(buffer_url).get('text')
            res_data = create_res_data(tos_data, 1)
            if len(tos_data) > 0:
                tos_utlis.put_string_to_tos(buffer_url, {'text': tos_data})

            has_comments = len(data.get("comments", [])) > 0
            res_ten = create_res_data(
                "WRITE,COMMENT" if has_comments else "WRITE",
                10
            )

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

        elif not tos_utlis.check_file_in_tos_buff(buffer_url):

            if data.get("duration") / 1000 / 60 > 20:
                res_data = create_res_data("该视频时长超出20min暂不支持提取", 1)
                yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
                return

            if tos_utlis.check_file_in_tos(f"ks/{data.get('video_id')}/{data.get('video_id')}.mp4"):

                url = f"https://douchacha-web.tos-cn-beijing.volces.com/ks/{data.get('video_id')}/{data.get('video_id')}.mp4"
                res_data = create_res_data("视频文案提取中", 3)
                yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
                recognizer = asr_utils.SpeechRecognizer()
                audio_result = recognizer.recognize_audio(url)
                if audio_result is None:
                    res_data = create_res_data("语音识别失败", 0)
                    yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
                else:

                    content = audio_result if len(audio_result) > 0 else "该视频没有文案"
                    res_data = create_res_data(content, 1)

                    if len(audio_result) > 0:
                        tos_utlis.put_string_to_tos(buffer_url, {'text': audio_result})

                    has_comments = len(data.get("comments", [])) > 0
                    res_ten = create_res_data(
                        "WRITE,COMMENT" if has_comments else "WRITE",
                        10
                    )

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

        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')


############################################################
# 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:
            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')

        res_data = create_res_data("视频文案提取中", 3)
        yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')

        buffer_url = f"bilibili/{data.get('bvid')}/{data.get('bvid')}.json"
        if tos_utlis.check_file_in_tos_buff(buffer_url):

            tos_data = tos_utlis.get_string_from_tos(buffer_url).get('text')
            res_data = create_res_data(tos_data, 1)
            if len(tos_data) > 0:
                tos_utlis.put_string_to_tos(buffer_url, {'text': tos_data})

            has_comments = len(data.get("comments", [])) > 0
            res_ten = create_res_data(
                "WRITE,COMMENT" if has_comments else "WRITE",
                10
            )

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

        elif not tos_utlis.check_file_in_tos_buff(buffer_url):

            if data.get("duration") / 60 > 50:
                res_data = create_res_data("该视频时长超出20min暂不支持提取", 1)
                yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
                return

            if tos_utlis.check_file_in_tos(f"bilibili/{data.get('bvid')}/{data.get('bvid')}.mp3"):

                url = f"https://douchacha-web.tos-cn-beijing.volces.com/bilibili/{data.get('bvid')}/{data.get('bvid')}.mp3"

                recognizer = asr_utils.SpeechRecognizer()

                audio_result = recognizer.recognize_audio(url)

                if audio_result is None:
                    res_data = create_res_data("语音识别失败", 0)
                    yield f"data: {json.dumps(res_data, ensure_ascii=False)}\n\n".encode('utf-8')
                else:

                    content = audio_result if len(audio_result) > 0 else "该视频没有文案"
                    res_data = create_res_data(content, 1)

                    if len(audio_result) > 0:
                        tos_utlis.put_string_to_tos(buffer_url, {'text': audio_result})

                    has_comments = len(data.get("comments", [])) > 0
                    res_ten = create_res_data(
                        "WRITE,COMMENT" if has_comments else "WRITE",
                        10
                    )

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

        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_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)
        else:
            res_data = create_res_data("请输入要处理的视频或图文链接", 1)
            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"请提供视频或者图文链接", 1)
        yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n".encode('utf-8')


def extract_mp4_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


def extract_user_contents(dialogues):
    user_contents = []
    for item in dialogues:
        if 'role' in item and 'content' in item:
            if item['role'] == 'user':
                user_contents.append(item['content'])
    return user_contents


