"""
Jingrow Cloud API 调用工具
用于与 Jingrow Cloud 进行API通信
"""

import requests
from jingrow.config import Config
from jingrow.utils.auth import get_jingrow_cloud_api_headers, get_jingrow_cloud_api_url


def call_jingrow_model(prompt: str,
                       image_urls: list = None,
                       ai_temperature: float = None,
                       ai_top_p: float = None,
                       ai_system_message: str = None,
                       max_tokens: int = None):
    """
    调用 Jingrow Cloud `jchat/chat` API，对齐 jingrow 原版实现
    返回: { 'success': True, 'response': str } 或 { 'success': False, 'error': str }
    """
    try:
        api_url = f"{get_jingrow_cloud_api_url()}/jchat/chat"
        headers = get_jingrow_cloud_api_headers()
        if not headers:
            return {"success": False, "error": "Jingrow API 未设置，请在 AI设置 中设置 Jingrow Api Key 和 Jingrow Api Secret"}
        
        temperature = ai_temperature or 0.7
        top_p = ai_top_p or 0.9
        system_message = ai_system_message or "你是一个有用的AI助手。"
        
        if image_urls and len(image_urls) > 0:
            model = "jingrow-chat-vision"
            content = [{"type": "text", "text": prompt}]
            for img_url in image_urls:
                if img_url:
                    content.append({"type": "image_url", "image_url": {"url": img_url}})
            payload = {
                "model": model,
                "messages": [
                    {"role": "system", "content": system_message},
                    {"role": "user", "content": content}
                ],
                "temperature": temperature,
                "top_p": top_p,
                "max_tokens": max_tokens or 2048
            }
        else:
            model = "jingrow-chat"
            payload = {
                "model": model,
                "messages": [
                    {"role": "system", "content": system_message},
                    {"role": "user", "content": prompt}
                ],
                "temperature": temperature,
                "top_p": top_p,
                "max_tokens": max_tokens or 2048
            }
        
        resp = requests.post(api_url, json=payload, headers=headers, timeout=60)
        if resp.status_code != 200:
            return {"success": False, "error": f"HTTP {resp.status_code}: {resp.text}"}
        
        try:
            resp_json = resp.json()
            message = resp_json.get("choices", [{}])[0].get("message", {}).get("content", "")
            if not message:
                data = resp_json.get("data") or (resp_json.get("message") or {}).get("data")
                if isinstance(data, dict):
                    message = data.get("content", "")
                elif isinstance(data, str):
                    message = data
            return {"success": True, "response": message or ""}
        except Exception:
            return {"success": False, "error": "AI响应解析失败"}
    except Exception as e:
        return {"success": False, "error": f"调用AI模型异常: {str(e)}"}


def call_chatgpt_model(prompt: str,
                       image_urls: list = None,
                       ai_temperature: float = None,
                       ai_top_p: float = None,
                       ai_system_message: str = None,
                       max_tokens: int = None,
                       model: str = None):
    """调用 ChatGPT 模型"""
    try:
        api_url = getattr(Config, 'CHATGPT_API_URL', None) or "https://api.openai.com/v1/chat/completions"
        api_key = getattr(Config, 'CHATGPT_API_KEY', None)
        model_name = model or getattr(Config, 'CHATGPT_API_MODEL', None) or "gpt-4o"
        if not api_key:
            return {"success": False, "error": "ChatGPT API 未配置"}
        content = [{"type": "text", "text": prompt}]
        if image_urls:
            for img in image_urls:
                if img:
                    content.append({"type": "image_url", "image_url": {"url": img}})
        payload = {
            "model": model_name,
            "messages": [
                {"role": "system", "content": ai_system_message or "你是一个有用的AI助手。"},
                {"role": "user", "content": content}
            ],
            "temperature": ai_temperature if ai_temperature is not None else 0.7,
            "top_p": ai_top_p if ai_top_p is not None else 0.9,
            "max_tokens": max_tokens or 2048
        }
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}"
        }
        resp = requests.post(api_url, headers=headers, json=payload, timeout=60)
        if resp.status_code != 200:
            return {"success": False, "error": f"HTTP {resp.status_code}: {resp.text}"}
        try:
            result = resp.json()
            message = result.get("choices", [{}])[0].get("message", {}).get("content", "")
            return {"success": True, "response": message or ""}
        except Exception:
            return {"success": False, "error": "ChatGPT 响应解析失败"}
    except Exception as e:
        return {"success": False, "error": f"调用ChatGPT异常: {str(e)}"}


def call_deepseek_model(prompt: str,
                        image_urls: list = None,
                        ai_temperature: float = None,
                        ai_top_p: float = None,
                        ai_system_message: str = None,
                        max_tokens: int = None,
                        model: str = None):
    """调用 DeepSeek 模型"""
    try:
        api_url = getattr(Config, 'DEEPSEEK_API_URL', None)
        api_key = getattr(Config, 'DEEPSEEK_API_KEY', None)
        model_name = model or getattr(Config, 'DEEPSEEK_API_MODEL', None) or "deepseek-chat"
        if not api_url or not api_key:
            return {"success": False, "error": "DeepSeek API 未配置"}
        content = [{"type": "text", "text": prompt}]
        if image_urls:
            for img in image_urls:
                if img:
                    content.append({"type": "image_url", "image_url": {"url": img}})
        payload = {
            "model": model_name,
            "messages": [
                {"role": "system", "content": ai_system_message or "你是一个有用的AI助手。"},
                {"role": "user", "content": content}
            ],
            "temperature": ai_temperature if ai_temperature is not None else 0.7,
            "top_p": ai_top_p if ai_top_p is not None else 0.9,
            "max_tokens": max_tokens or 2048
        }
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}"
        }
        resp = requests.post(api_url, headers=headers, json=payload, timeout=60)
        if resp.status_code != 200:
            return {"success": False, "error": f"HTTP {resp.status_code}: {resp.text}"}
        try:
            result = resp.json()
            message = result.get("choices", [{}])[0].get("message", {}).get("content", "")
            return {"success": True, "response": message or ""}
        except Exception:
            return {"success": False, "error": "DeepSeek 响应解析失败"}
    except Exception as e:
        return {"success": False, "error": f"调用DeepSeek异常: {str(e)}"}


def call_doubao_model(prompt: str,
                      image_urls: list = None,
                      ai_temperature: float = None,
                      ai_top_p: float = None,
                      ai_system_message: str = None,
                      max_tokens: int = None,
                      model: str = None):
    """调用豆包模型"""
    try:
        api_url = getattr(Config, 'DOUBAO_API_URL', None) or getattr(Config, 'DOUBAO_API_URL'.upper(), None)
        api_key = getattr(Config, 'DOUBAO_API_KEY', None) or getattr(Config, 'DOUBAO_API_KEY'.upper(), None)
        model_name = model or getattr(Config, 'DOUBAO_API_MODEL', None) or "doubao-pro-32k-241215"
        if not api_url or not api_key:
            return {"success": False, "error": "豆包 API 未配置"}
        content = [{"type": "text", "text": prompt}]
        if image_urls:
            for img in image_urls:
                if img:
                    content.append({"type": "image_url", "image_url": {"url": img}})
        payload = {
            "model": model_name,
            "messages": [
                {"role": "system", "content": ai_system_message or "你是一个有用的AI助手。"},
                {"role": "user", "content": content}
            ],
            "temperature": ai_temperature if ai_temperature is not None else 0.7,
            "top_p": ai_top_p if ai_top_p is not None else 0.9,
            "max_tokens": max_tokens or 2048
        }
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}"
        }
        resp = requests.post(api_url, headers=headers, json=payload, timeout=60)
        if resp.status_code != 200:
            return {"success": False, "error": f"HTTP {resp.status_code}: {resp.text}"}
        try:
            result = resp.json()
            message = result.get("choices", [{}])[0].get("message", {}).get("content", "")
            return {"success": True, "response": message or ""}
        except Exception:
            return {"success": False, "error": "豆包 响应解析失败"}
    except Exception as e:
        return {"success": False, "error": f"调用豆包异常: {str(e)}"}


def call_jembedding(texts: list):
    """
    调用 Jingrow Cloud `jembedding/batch` API，文本转向量
    返回: { 'success': True, 'data': list } 或 { 'success': False, 'error': str }
    """
    try:
        api_url = f"{get_jingrow_cloud_api_url()}/jembedding/batch"
        headers = get_jingrow_cloud_api_headers()
        if not headers:
            return {"success": False, "error": "Jingrow API 未设置，请在 AI设置 中设置 Jingrow Api Key 和 Jingrow Api Secret"}
        
        payload = {"items": texts}
        
        resp = requests.post(api_url, json=payload, headers=headers, stream=True, timeout=180)
        if resp.status_code != 200:
            return {"success": False, "error": f"HTTP {resp.status_code}: {resp.text}"}
        
        results = []
        for line in resp.iter_lines():
            if line:
                try:
                    import json
                    result = json.loads(line)
                    results.append(result)
                except Exception:
                    continue
        
        return {"success": True, "data": results}
    except Exception as e:
        return {"success": False, "error": f"调用Embedding API异常: {str(e)}"}


def call_ai_model(prompt: str,
                  text_model: str = None,
                  ai_temperature: float = None,
                  ai_top_p: float = None,
                  ai_system_message: str = None,
                  max_tokens: int = None,
                  image_urls: list = None):
    """
    统一调度：根据 text_model 路由到具体模型（jingrow/deepseek/doubao/chatgpt）。
    与 jingrow 原版 utils.call_ai_model 的分流思路一致。
    """
    model_type = (text_model or "jingrow").lower()
    if "jingrow" in model_type:
        return call_jingrow_model(
            prompt,
            image_urls=image_urls,
            ai_temperature=ai_temperature,
            ai_top_p=ai_top_p,
            ai_system_message=ai_system_message,
            max_tokens=max_tokens
        )
    if "deepseek" in model_type:
        return call_deepseek_model(prompt, image_urls, ai_temperature, ai_top_p, ai_system_message, max_tokens)
    if "doubao" in model_type or "doudou" in model_type:
        return call_doubao_model(prompt, image_urls, ai_temperature, ai_top_p, ai_system_message, max_tokens)
    # 默认走 ChatGPT
    return call_chatgpt_model(prompt, image_urls, ai_temperature, ai_top_p, ai_system_message, max_tokens)
