import json
import os


from aidso_geo.utils.tos_utils import put_string_to_tos
from aidso_geo.utils import bh_utils
from aidso_geo.utils import url_utils


def deepseek_process_quote(url_list):
    quto_list = []

    for item in url_list:
        raw_data = {
            "url": item.get('url', ''),
            "title": item.get('title', ''),
            "snippet": item.get('snippet', ''),
            "index": item.get('cite_index', ''),
            "published_at": item.get('published_at', ''),
            "site_name": item.get('site_name', ''),
            "site_icon": item.get('site_icon', ''),
        }
        quto_list.append(raw_data)
    return quto_list


def deepseek_android_process_quote(url_list):
    quto_list = []

    for item in url_list:
        raw_data = {
            "url": item.get('url', ''),
            "title": item.get('title', ''),
            "snippet": item.get('snippet', ''),
            "index": item.get('cite_index', ''),
            "published_at": item.get('published_at', ''),
            "site_name": item.get('site_name', ''),
            "site_icon": item.get('site_icon', ''),
        }
        quto_list.append(raw_data)
    return quto_list


def doubao_android_process_quote(url_list):
    quto_list = []

    for item in url_list:
        raw_data = {
            "url": item.get('url', '') or item.get('main_site_url',''),
            "title": item.get('title', '') or item.get('video_captions',''),
            "snippet": item.get('summary', '')  or item.get('video_captions',''),
            "index": item.get('index', ''),
            "published_at": item.get('publish_time_second', ''),
            "site_name": item.get('sitename', '') or item.get('source_app_name', ''),
            "site_icon": item.get('logo_url', '') or  item.get('source_app_icon', ''),
        }
        quto_list.append(raw_data)
    return quto_list


def doubao_android_process_rich_media(url_list):
    quto_list = []

    for item in url_list:
        video_id = item.get('item_id', '')
        raw_data = {
            "video_id": video_id,
            "video_captions": item.get('video_captions', ''),
            "video_first_frame_image": item.get('video_first_frame_image', '') or item.get('cover').get('origin_cover').get('image_ori').get('url') or '',
            "main_site_url": item.get('main_site_url', '') or f'https://www.douyin.com/video/{video_id}',
            "source_app_name": item.get('source_app_name', '') or '抖音'
        }
        quto_list.append(raw_data)
    return quto_list


def yuanbao_android_process_rich_media(url_list):
    quto_list = []

    for item in url_list:
        video_id = item.get('mediaId', '')
        raw_data = {
            "video_id": video_id,
            "video_captions": item.get('title', ''),
            "video_first_frame_image": item.get('url', '') or item.get('resourceUrl') or '',
            "main_site_url": '',
            "source_app_name": '视频号'
        }
        quto_list.append(raw_data)
    return quto_list

def doubao_process_rich_media(url_list):
    quto_list = []

    for item in url_list:
        raw_data = {
            "video_id": item.get('item_id', ''),
            "video_captions": item.get('video_captions', ''),
            "video_first_frame_image": item.get('video_first_frame_image', ''),
            "main_site_url": item.get('main_site_url', ''),
            "source_app_name": item.get('source_app_name', '')
        }
        quto_list.append(raw_data)
    return quto_list

def douyinai_process_rich_media(url_list):
    quto_list = []

    for item in url_list:
        raw_data = {
            "video_id": item.get('id', ''),
            "video_captions": item.get('title', ''),
            "video_first_frame_image": item.get('url_struct').get("url_list")[0],
            "main_site_url": "https://m.douyin.com/share/video/"+item.get('id', ''),
            "source_app_name": item.get('source_app_name', '抖音')
        }
        quto_list.append(raw_data)
    return quto_list


def qianwen_android_process_rich_media(url_list):
    quto_list = []
    for item in url_list:
        source_seq= item.get('source_seq', '')
        if isinstance(item.get('url'),list):
            for url in item.get('url'):
                raw_data = {
                "video_id": url.get('zhidaye_id', ''),
                "video_captions": url.get('title', ''),
                "video_first_frame_image": url.get('cover',''),
                "main_site_url": url.get('norm_url', '') or url.get('url', ''),
                "author": url.get('author', ''),
                "publishTime": url.get('publishTime', ''),
                "duration": url.get('duration', ''),
                "source_seq": source_seq
                }
                quto_list.append(raw_data)
    return quto_list


def qianwen_process_rich_media(url_list):
    quto_list = []
    for item in url_list:
        source_seq= item.get('source_seq', '')
        if isinstance(item.get('url'),list):
            for url in item.get('url'):
                raw_data = {
                "video_id": url.get('zhidaye_id', ''),
                "video_captions": url.get('title', ''),
                "video_first_frame_image": url.get('cover',''),
                "main_site_url": url.get('norm_url', '') or url.get('url', ''),
                "author": url.get('author', ''),
                "publishTime": url.get('publishTime', ''),
                "duration": url.get('duration', ''),
                "source_seq": source_seq
                }
                quto_list.append(raw_data)
    return quto_list

def baidu_ai_rich_media(url_list):
    quto_list = []
    for item in url_list:
        raw_data = {
            "video_id": item.get('nid', ''),
            "video_captions": item.get('title', ''),
            "video_first_frame_image": item.get('src', '') or item.get('thumbnail').get('src'),
            "main_site_url": item.get('linkInfo').get('originUrl') or item.get('linkInfo').get('href') or '',
            "source_app_name": '全民小视频'
        }
        quto_list.append(raw_data)
    return quto_list



def doubao_process_quote(url_list):
    quto_list = []

    for item in url_list:
        raw_data = {
            "url": item.get('text_card',{}).get('url', '') or item.get('video_card',{}).get('main_site_url'),
            "title": item.get('text_card',{}).get('title', '') or item.get('video_card',{}).get('video_captions'),
            "snippet": item.get('text_card',{}).get('summary', '') or item.get('video_card',{}).get('summary',''),
            "index": item.get('text_card',{}).get('index', '') or item.get('video_card',{}).get('index', ''),
            "published_at": item.get('text_card',{}).get('publish_time_second', '') or item.get('video_card',{}).get('publish_time_second', ''),
            "site_name": item.get('text_card',{}).get('sitename', '') or item.get('video_card',{}).get('source_app_name', ''),
            "site_icon": item.get('text_card',{}).get('logo_url', '') or item.get('video_card',{}).get('source_app_icon', ''),
        }
        quto_list.append(raw_data)
    return quto_list

def baiduai_process_quote(url_list):
    quto_list = []

    for index, item in enumerate(url_list):
        raw_data = {
            "url": item.get('url', ''),
            "title": item.get('text', ''),
            "snippet": item.get('abstract', ''),
            "index": index,
            "published_at": item.get('published_at', ''),
            "site_name": item.get('source', ''),
            "site_icon": item.get('icon', ''),
        }
        quto_list.append(raw_data)
    return quto_list

def douyinai_process_quote(url_list):
    quto_list = []

    for index, item in enumerate(url_list):

        site_name = item.get("site_name", "")
        aweme_id = item.get("aweme_id", "")
        default_url = item.get("url", "")

        if site_name == "抖音视频" and aweme_id:
            final_url = f"https://www.douyin.com/video/{aweme_id}"
        else:
            final_url = default_url

        raw_data = {
            "url": final_url ,
            "title": item.get('title', ''),
            "snippet": item.get('abstract', ''),
            "index": index,
            "published_at": item.get('published_at', ''),
            "site_name": site_name,
            "site_icon": item.get('logo_url', ''),
        }
        quto_list.append(raw_data)
    return quto_list

def qianwen_android_process_quote(url_list):
    quto_list = []

    for index, item in enumerate(url_list):
        source_seq= item.get('source_seq', '')
        for url in item.get('url'):
            content = url.get('content')
            if content:
                if isinstance(content.get('list'),list):
                    for c in content.get('list'):
                        raw_data = {
                            "url": c.get('url', ''),
                            "title": c.get('title', ''),
                            "snippet": c.get('summary', ''),
                            "index": index,
                            "published_at": c.get('publish_time', ''),
                            "site_name": c.get('name', ''),
                            "site_icon": c.get('icon', ''),
                            "source_seq": source_seq or url.get('source_seq'),
                        }
                        quto_list.append(raw_data)
    return quto_list

def yuanbao_process_quote(url_list):
    quto_list = []

    for item in url_list:
        raw_data = {
            "url": item.get('url', ''),
            "title": item.get('title', ''),
            "snippet": item.get('quote', ''),
            "index": item.get('index', ''),
            "published_at": item.get('publish_time', ''),
            "site_name": item.get('web_site_name', ''),
            "site_icon": item.get('icon_url', ''),
        }
        quto_list.append(raw_data)
    return quto_list

def yuanbao_android_process_quote(url_list):
    quto_list = []

    for item in url_list:
        raw_data = {
            "url": item.get('url', ''),
            "title": item.get('title', ''),
            "snippet": item.get('quote', ''),
            "index": item.get('index', ''),
            "published_at": item.get('publish_time', ''),
            "site_name": item.get('web_site_name', ''),
            "site_icon": item.get('icon_url', ''),
        }
        quto_list.append(raw_data)
    return quto_list

def xiaohongshu_android_process_quote(url_list):
    quto_list = []

    for index, item in enumerate(url_list):
        url = ""
        id = item.get('id')
        if id:
            url =  "https://www.xiaohongshu.com/explore/"+id
        raw_data = {
            "url": url,
            "title": item.get('title', ''),
            "snippet": item.get('content', ''),
            "index": index,
            "published_at": item.get('time', ''),
            "site_name": '小红书',
            "site_icon": 'www.xiaohongshu.com',
        }
        quto_list.append(raw_data)
    return quto_list

def qianwen_process_quote(url_list):
    quto_list = []

    for index, item in enumerate(url_list):
        raw_data = {
            "url": item.get('url', ''),
            "title": item.get('title', ''),
            "snippet": item.get('body', ''),
            "index": index,
            "published_at": item.get('time', ''),
            "site_name": item.get('host_name', ''),
            "site_icon": item.get('host_logo', ''),
        }
        quto_list.append(raw_data)
    return quto_list


def kimi_process_quote(url_list):
    quto_list = []

    for index, item in enumerate(url_list):
        raw_data = {
            "url": item.get('url', ''),
            "title": item.get('title', '') or item.get('site_name', ''),
            "snippet": item.get('snippet', ''),
            "index": item.get('refIndex') or item.get('id',index),
            "published_at": item.get('publishTime', ''),
            "site_name": item.get('siteName', ''),
            "site_icon": item.get('iconurl', ''),
        }
        quto_list.append(raw_data)
    return quto_list


def wenxin_process_quote(url_list):
    quto_list = []

    for index, item in enumerate(url_list):
        raw_data = {
            "url": item.get('url', ''),
            "title": item.get('title', 'PDF'),
            "snippet": item.get('siteAbstract', '') or item.get('wild_abstract', ''),
            "index": item.get('index', '') or index,
            "published_at": item.get('publishTime', '')  or item.get('date', ''),
            "site_name": item.get('name', '') or item.get('site', ''),
            "site_icon": item.get('icon', '') or item.get('site_icon', ''),
        }
        quto_list.append(raw_data)
    return quto_list


def get_target_dir(full_path):
    dir_part = os.path.dirname(full_path)

    target_dir = dir_part + os.sep

    return target_dir


def save_data_to_tos(target_dir, content, file_name):
    if not content:
        return
    platform = target_dir.split('/')[2]
    if file_name == "rich_media_block.txt":
        if platform == 'DOUBA':
            content = doubao_android_process_rich_media(content)
        if platform == 'DB':
            content = doubao_process_rich_media(content)
        if platform == 'DYAI':
            content = douyinai_process_rich_media(content)
        if platform =='TYQWA':
            content = qianwen_android_process_rich_media(content)
        if platform =='BDAI':
            content = baidu_ai_rich_media(content)
        if platform =='TYQW':
            content = qianwen_process_rich_media(content)
        if platform == 'TXYBA':
            content = yuanbao_android_process_rich_media(content)

    if file_name == "quote.txt":
        if platform == 'DB':
            content = doubao_process_quote(content)
        elif platform == 'DP':
            content = deepseek_process_quote(content)
        elif platform == 'TXYB':
            content = yuanbao_process_quote(content)
        elif platform == 'TYQW':
            content = qianwen_process_quote(content)
        elif platform == 'KIMI':
            content = kimi_process_quote(content)
        elif platform == 'WXYY':
            content = wenxin_process_quote(content)
        elif platform == 'BDAI':
            content = baiduai_process_quote(content)
        elif platform == 'DPA':
            content = deepseek_android_process_quote(content)
        elif platform == 'DOUBA':
            content = doubao_android_process_quote(content)
        elif platform == 'DYAI':
            content = douyinai_process_quote(content)
        elif platform == 'TYQWA':
            content = qianwen_android_process_quote(content)
        elif platform == 'TXYBA':
            content = yuanbao_android_process_quote(content)
        elif platform == 'XHSA':
            content = xiaohongshu_android_process_quote(content)

        else:
            content = doubao_process_quote(content)
        task_id = target_dir.split('/')[1]

        urls = []

        for c in content:
            c['task_id'] = task_id
            c['platform'] = platform
            u = c.get('url')
            if isinstance(u, str) and u.startswith('http'):
                urls.append(u)
            else:
                urls.append(c.get('title'))
        url_ids_map = url_utils.generate_numeric_url_id_v2(urls)

        for c in content:
            u = c.get('url')
            if isinstance(u, str) and u.startswith('http'):
                key = u
            else:
                key = c.get('title')
            c['quto_id'] = url_ids_map.get(key)

        bh_utils.insert_data("geo_quote_result_v2", content)

    full_file_path = f"{target_dir}{file_name}"
    put_string_to_tos(full_file_path, content)


def process_and_save_files(file_path, search_keyword, url_list, think_content, response_content, suggestions,rich_media_block=None):
    target_dir = get_target_dir(file_path)
    data_config = [
        (search_keyword, "search_keyword.txt"),  # 搜索关键词 → search_keyword.txt
        (url_list, "quote.txt"),  # URL列表 → quote.txt
        (think_content, "think.txt"),  # 思考内容 → think.txt
        (response_content, "context.txt"),  # 响应内容 → context.txt
        (suggestions, "suggestions.txt")  # 响应内容 → context.txt
    ]
    if rich_media_block is not None:
        data_config.append((rich_media_block, "rich_media_block.txt"))

    for content, file_name in data_config:
        save_data_to_tos(target_dir, content, file_name)

def ai_process_quote(url_list):
    quto_list = []

    for index, item in enumerate(url_list):
        raw_data = {
            "url": item.get('url', ''),
            "title": item.get('title', ''),
            "snippet": item.get('snippet', ''),
            "index": item.get('index', '') or index,
            "published_at": item.get('published_at',''),
            "site_name": item.get('site_name', ''),
            "site_icon": item.get('site_icon', ''),
        }
        quto_list.append(raw_data)
    return quto_list


def save_data_to_tos_ai(target_dir, content, file_name):
    if not content:
        return
    platform = target_dir.split('/')[2]

    if file_name == "quote.txt":

        content = ai_process_quote(content)
        task_id = target_dir.split('/')[1]

        urls = []

        for c in content:
            c['task_id'] = task_id
            c['platform'] = platform
            u = c.get('url')
            if isinstance(u, str) and u.startswith('http'):
                urls.append(u)
            else:
                urls.append(c.get('title'))
        url_ids_map = url_utils.generate_numeric_url_id_v2(urls)

        for c in content:
            u = c.get('url')
            if isinstance(u, str) and u.startswith('http'):
                key = u
            else:
                key = c.get('title')
            c['quto_id'] = url_ids_map.get(key)

        bh_utils.insert_data("geo_quote_result_v2", content)

    full_file_path = f"{target_dir}{file_name}"
    put_string_to_tos(full_file_path, content)


def process_and_save_files_ai(file_path, search_keyword, url_list, think_content, response_content, suggestions,rich_media_block=None):
    target_dir = get_target_dir(file_path)
    data_config = [
        (search_keyword, "search_keyword.txt"),  # 搜索关键词 → search_keyword.txt
        (url_list, "quote.txt"),  # URL列表 → quote.txt
        (think_content, "think.txt"),  # 思考内容 → think.txt
        (response_content, "context.txt"),  # 响应内容 → context.txt
        (suggestions, "suggestions.txt")  # 响应内容 → context.txt
    ]
    for content, file_name in data_config:
        save_data_to_tos_ai(target_dir, content, file_name)
