import requests
from abc import ABC
import logging
import json

logger = logging.getLogger(__name__)

res = {
    "event": "message",
    "task_id": "49c9ea1b-7b43-475b-a680-d769fb238a45",
    "id": "432ab98e-5e36-4a29-abe5-e01281c3678c",
    "message_id": "432ab98e-5e36-4a29-abe5-e01281c3678c",
    "mode": "completion",
    "answer": '```\n{\n  "description": "该API的具体功能描述暂时不明确，因为提供的API信息 \'今天打老虎啊按时啊啊\' 并不是有效的API名称或描述。请提供正确的API名称和相关输入输出信息，以便我能为其补充完善的API描述。"\n}\n```',
    "metadata": {
        "usage": {
            "prompt_tokens": 73,
            "prompt_unit_price": "0.0",
            "prompt_price_unit": "0.0",
            "prompt_price": "0.0",
            "completion_tokens": 61,
            "completion_unit_price": "0.0",
            "completion_price_unit": "0.0",
            "completion_price": "0.0",
            "total_tokens": 134,
            "total_price": "0.0",
            "currency": "USD",
            "latency": 1.896302318200469,
        }
    },
    "created_at": 1747233054,
}


def process_answer_code_block(data):
    try:
        # 获取answer字段
        answer = data.get("answer", "")

        # 检查answer是否是代码块格式
        if answer.startswith("```") and answer.endswith("```"):
            # 移除代码块标记并解析JSON
            code_content = answer.strip("```").strip()
            json_data = json.loads(code_content)

            # 获取description字段
            if "description" in json_data:
                return json_data["description"]

        # 如果不是预期格式，则返回原始answer
        return data.get("answer", data)
    except Exception as e:
        logger.warning(f"处理答案代码块时出错: {str(e)}")
        # 发生错误时返回原始数据
        return data.get("answer", data)


def chat_message_test(
    api_key,
    inputs={},
    response_mode="blocking",
    conversation_id=None,
    userId="pp666",
    files=None,
):
    url = "https://ops.lzwcai.com/v1/completion-messages"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    }
    data = {
        "inputs": inputs,
        "response_mode": response_mode,
        "user": userId,
    }
    if conversation_id:
        data["conversation_id"] = conversation_id
    if response_mode == "streaming":
        response = requests.post(
            url, headers=headers, json=data, stream=response_mode == "streaming"
        )
        return response
    else:
        response = requests.post(url, headers=headers, json=data)
        return response.json()


if __name__ == "__main__":
    print("开始执行主程序")
    try:
        print("准备调用chat_message方法")
        res = chat_message_test(
            api_key="app-Ppemii3c0ROPoLvRwskgZ7Il",
            inputs={"query": "今天打老虎啊按时啊啊"},
            response_mode="streaming",
            userId="abc-123",
        )
        print("chat_message方法调用完成")

        # 打印响应内容
        print("响应内容:", res)
        # print(process_answer_code_block(res))
    except Exception as e:
        print(f"执行过程中出现错误: {e}")
