# -*- coding: utf-8 -*-
import requests
import json
import time
import requests
from loguru import logger
from aidso_geo.utils.robot_utils import feishu_tobot_sse

def normalize_thinking_type_ark(think):
    if str(think).strip() == "1":
        return "enabled"

    return "disabled"

def normalize_thinking_type_ali(think):
    if str(think).strip() == "1":
        return True

    return False
def parse_ark_response(resp):
    """
    解析ark Responses API 返回值，提取：
    1. 回答正文 response_content
    2. 思考过程 think_content
    3. 引用来源 url_list
    4. 搜索关键词 search_keywords
    DB DOUBA DP DPA
    """

    response_content = ""
    think_content = ""
    url_list = []
    search_keywords = []

    output_list = resp.get("output", [])

    for item in output_list:
        item_type = item.get("type")

        # 1. 提取思考过程
        if item_type == "reasoning":
            summary_list = item.get("summary", [])
            for summary in summary_list:
                if summary.get("type") == "summary_text":
                    text = summary.get("text")
                    if text:
                        think_content+=(text)

        # 2. 提取搜索关键词
        elif item_type == "web_search_call":
            action = item.get("action", {})
            query = action.get("query")
            if query:
                # 你的 query 里是用 ; 拼接的多个搜索词
                keywords = [
                    q.strip()
                    for q in query.replace("；", ";").split(";")
                    if q.strip()
                ]
                search_keywords.extend(keywords)

        # 3. 提取回答正文和引用来源
        elif item_type == "message":
            content_list = item.get("content", [])

            for content in content_list:
                # 回答正文
                if content.get("type") == "output_text":
                    text = content.get("text")
                    if text:
                        response_content+=text

                    # 引用来源
                    annotations = content.get("annotations", [])
                    for ann in annotations:
                        if ann.get("type") == "url_citation":
                            url_list.append({
                                "title": ann.get("title", ""),
                                "url": ann.get("url", ""),
                                "site_name": ann.get("site_name", ""),
                                "publish_time": ann.get("publish_time", ""),
                                "summary": ann.get("summary", ""),
                                "logo_url": ann.get("logo_url", "")
                            })

    return (search_keywords, url_list, think_content, response_content)

def parse_tencent_response(resp):
    response_content = ""
    think_content = ""
    url_list = []
    search_keywords = []

    choices = resp.get("choices", [])

    for choice in choices:
        message = choice.get("message", {}) or {}

        content = message.get("content")
        if content:
            response_content += content

        reasoning_content = message.get("reasoning_content")
        if reasoning_content:
            think_content += reasoning_content

    return (search_keywords, url_list, think_content, response_content)

def parse_aliyun_response(resp):
    """
    解析阿里云百炼 qwen chat.completion 返回值，提取：
    1. 搜索关键词 search_keywords
    2. 引用来源 url_list
    3. 思考过程 think_content
    4. 回答正文 response_content

    返回结构保持和 parse_ark_response 一致：
    return (search_keywords, url_list, think_content, response_content)
    """

    response_content = ""
    think_content = ""
    url_list = []
    search_keywords = []

    choices = resp.get("choices", [])

    for choice in choices:
        message = choice.get("message", {}) or {}

        # 1. 回答正文
        content = message.get("content")
        if content:
            response_content += content

        # 2. 思考过程
        reasoning_content = message.get("reasoning_content")
        if reasoning_content:
            think_content += reasoning_content

        # 3. 如果后续阿里返回里带 annotations，也兼容一下
        annotations = message.get("annotations", [])
        for ann in annotations:
            if ann.get("type") in ("url_citation", "citation"):
                url_list.append({
                    "title": ann.get("title", ""),
                    "url": ann.get("url", ""),
                    "site_name": ann.get("site_name", ""),
                    "publish_time": ann.get("publish_time", ""),
                    "summary": ann.get("summary", ""),
                    "logo_url": ann.get("logo_url", "")
                })

    return (search_keywords, url_list, think_content, response_content)


def get_doubao_message(promp, think, max_retry=3):
    think_type = normalize_thinking_type_ark(think)

    url = "https://ark.cn-beijing.volces.com/api/v3/responses"

    headers = {
        'Authorization': 'Bearer ark-7afc3be2-37a8-47fd-9f02-996258a3d305-27da0',
        'Content-Type': 'application/json'
    }

    default_result = ([], [], "", "")
    for retry_index in range(1, max_retry + 1):
        payload = json.dumps({
            "model": "doubao-seed-2-1-turbo-260628",
            "stream": False,
            "tool_choice": {
                "type": "web_search"
            },
            "tools": [
                {
                    "type": "web_search",
                    "max_keyword": 10
                }
            ],
            "input": [
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "input_text",
                            "text": promp
                        }
                    ]
                }
            ],
            "thinking": {
                "type": think_type
            }
        }, ensure_ascii=False)

        try:
            response = requests.request(
                "POST",
                url,
                headers=headers,
                data=payload.encode("utf-8"),
                timeout=300
            )

            response.raise_for_status()
            json_response = response.json()

            result = parse_ark_response(json_response)

            response_content = result[3] if len(result) > 3 else ""

            if response_content and response_content.strip():
                return result



        except Exception as e:
            logger.error(f"第 {retry_index} 次请求异常：{e}")

        if retry_index < max_retry:
            time.sleep(2)

    return default_result

def get_deepseek_message(promp, think, max_retry=3):
    think_type = normalize_thinking_type_ark(think)
    url = "https://ark.cn-beijing.volces.com/api/v3/responses"

    headers = {
        'Authorization': 'Bearer ark-7afc3be2-37a8-47fd-9f02-996258a3d305-27da0',
        'Content-Type': 'application/json'
    }

    default_result = ([], [], "", "")
    for retry_index in range(1, max_retry + 1):
        payload = json.dumps({
            "model": "deepseek-v4-pro-260425",
            "stream": False,
            "tool_choice": {
                "type": "web_search"
            },
            "tools": [
                {
                    "type": "web_search",
                    "max_keyword": 10
                }
            ],
            "input": [
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "input_text",
                            "text": promp
                        }
                    ]
                }
            ],
            "thinking": {
                "type": think_type
            }
        }, ensure_ascii=False)

        try:
            response = requests.request(
                "POST",
                url,
                headers=headers,
                data=payload.encode("utf-8"),
                timeout=300
            )

            response.raise_for_status()
            json_response = response.json()

            result = parse_ark_response(json_response)

            response_content = result[3] if len(result) > 3 else ""

            if response_content and response_content.strip():
                return result


        except Exception as e:
            logger.error(f"第 {retry_index} 次请求异常：{e}")

        if retry_index < max_retry:
            time.sleep(2)

    return default_result

def get_yuanbao_message(promp, think, max_retry=3):

    think_type = normalize_thinking_type_ark(think)
    url = "https://tokenhub.tencentmaas.com/v1/chat/completions"
    headers = {
        'Authorization': 'Bearer sk-Pnc12sxc2H3kJkECTrp1lWhtUY5HYyVqSCxfUFzC8x2ghoCK',
        'Content-Type': 'application/json'
    }

    default_result = ([], [], "", "")

    for retry_index in range(1, max_retry + 1):
        payload = json.dumps({
            "model": "hy3-preview",
            "messages": [
                {
                    "role": "system",
                    "content": "你是一位得力的助手。"
                },
                {
                    "role": "user",
                    "content": promp
                }
            ],
            "thinking": {
                "type": think_type
            },
            "stream": False
        }, ensure_ascii=False)

        try:
            response = requests.request(
                "POST",
                url,
                headers=headers,
                data=payload.encode("utf-8"),
                timeout=300
            )

            response.raise_for_status()
            json_response = response.json()


            result = parse_tencent_response(json_response)

            response_content = result[3] if result and len(result) > 3 else ""

            if response_content and response_content.strip():
                return result

        except Exception as e:
            logger.error(f"第 {retry_index} 次请求异常：{e}")

        if retry_index < max_retry:
            time.sleep(2)

    return default_result

def get_kimi_message(promp, think, max_retry=3):
    think_type = normalize_thinking_type_ark(think)
    url = "https://tokenhub.tencentmaas.com/v1/chat/completions"

    headers = {
        'Authorization': 'Bearer sk-Pnc12sxc2H3kJkECTrp1lWhtUY5HYyVqSCxfUFzC8x2ghoCK',
        'Content-Type': 'application/json'
    }

    default_result = ([], [], "", "")

    for retry_index in range(1, max_retry + 1):
        payload = json.dumps({
            "model": "kimi-k2.6",
            "messages": [
                {
                    "role": "system",
                    "content": "你是一位得力的助手。"
                },
                {
                    "role": "user",
                    "content": promp
                }
            ],
            "thinking": {
                "type": think_type
            },
            "stream": False
        }, ensure_ascii=False)

        try:
            response = requests.request(
                "POST",
                url,
                headers=headers,
                data=payload.encode("utf-8"),
                timeout=300
            )

            response.raise_for_status()
            json_response = response.json()


            result = parse_tencent_response(json_response)

            response_content = result[3] if result and len(result) > 3 else ""

            if response_content and response_content.strip():
                return result

        except Exception as e:
            logger.error(f"第 {retry_index} 次请求异常：{e}")

        if retry_index < max_retry:
            time.sleep(2)

    return default_result


def get_qianwewn_message(promp, think, max_retry=3):

    think_type = normalize_thinking_type_ali(think)
    url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"

    headers = {
        "Authorization": "Bearer sk-eed87fdb2c8e42d79353ba345db83d0a",
        "Content-Type": "application/json"
    }

    default_result = ([], [], "", "")

    for retry_index in range(1, max_retry + 1):
        payload = json.dumps({
            "model": "qwen3.7-max",
            "messages": [
                {
                    "role": "system",
                    "content": "你是一位得力的中文助手"
                },
                {
                    "role": "user",
                    "content": promp
                }
            ],
            "stream": False,
            "enable_thinking": think_type
        }, ensure_ascii=False)

        try:
            response = requests.post(
                url,
                headers=headers,
                data=payload.encode("utf-8"),
                timeout=300
            )

            response.raise_for_status()
            json_response = response.json()

            result = parse_aliyun_response(json_response)

            response_content = result[3] if result and len(result) > 3 else ""

            if response_content and response_content.strip():
                return result

        except Exception as e:
            logger.error(f"第 {retry_index} 次请求异常：{e}")

        if retry_index < max_retry:
            time.sleep(2)

    return default_result


MAX_POLL = 5
POLL_INTERVAL_SEC = 30

def get_parse_sse(platform, task_id):
    url = f"http://115.191.66.107:8894/parse_sse?platform={platform}&sse_url=https://douchacha-web.tos-cn-beijing.volces.com/geo/{task_id}/{platform}/original.text"
    payload = {}
    headers = {}

    response = requests.request("GET", url, headers=headers, data=payload)
    feishu_tobot_sse(url + "    触发sse解析接口")
    return response.json()


def get_parse_sse_result(platform, task_id):
    response_data = get_parse_sse(platform, task_id)

    if not response_data.get("ok"):
        return ("", [], [], "",[])
    else:
        for i in range(MAX_POLL):
            code = response_data.get("code")
            data = response_data.get("data")
            if code == 200:
                context = data.get('context')
                quote = data.get('quote')
                suggestions = data.get('suggestions')
                think = data.get('think')
                search_word = data.get('search_word')
                if len(think) < 30:
                    think = ""
                return (context, quote, suggestions, think, search_word)
            if i == MAX_POLL - 1:
                return ("", [], [], "",[])

            time.sleep(POLL_INTERVAL_SEC)


if __name__ == '__main__':

    print(get_deepseek_message("防晒霜推荐",1))
    # print(get_doubao_message("防晒霜推荐","disabled"))
