import os
import json
from django.http import StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from openai import OpenAI

# 初始化客户端 (硬编码 API Key)
API_KEY = "sk-ca7ca2c355ce408a809b77f8f8911700"
BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"

client = OpenAI(
    api_key=API_KEY,
    base_url=BASE_URL,
)


def stream_generator(user_input):
    """
    生成器函数，用于流式返回 DeepSeek 的响应
    """
    try:
        messages = [
            {"role": "system", "content": "你是一个运行在技术博客上的智能助手，请用简洁、专业的技术语言回答用户的问题。"},
            {"role": "user", "content": user_input}
        ]

        completion = client.chat.completions.create(
            model="deepseek-v3.2-exp",  # 使用指定的模型
            messages=messages,
            extra_body={"enable_thinking": True},  # 开启思考模式
            stream=True,
            stream_options={"include_usage": True},
        )

        for chunk in completion:
            # 检查是否有内容
            if not chunk.choices:
                continue

            delta = chunk.choices[0].delta

            # 处理思考过程 (Reasoning Content)
            if hasattr(delta, "reasoning_content") and delta.reasoning_content:
                # 发送思考片段，标记为 type: thinking
                data = json.dumps({
                    "type": "thinking",
                    "content": delta.reasoning_content
                })
                yield f"data: {data}\n\n"

            # 处理正式回复 (Content)
            if hasattr(delta, "content") and delta.content:
                # 发送回复片段，标记为 type: answer
                data = json.dumps({
                    "type": "answer",
                    "content": delta.content
                })
                yield f"data: {data}\n\n"

    except Exception as e:
        error_msg = json.dumps({"type": "error", "content": str(e)})
        yield f"data: {error_msg}\n\n"


@csrf_exempt  # 简单起见暂时免除CSRF，或者需要在前端传递 csrftoken
@require_POST
def chat_api(request):
    try:
        data = json.loads(request.body)
        user_input = data.get('message', '')

        if not user_input:
            return StreamingHttpResponse("No input provided", status=400)

        # 使用 StreamingHttpResponse 实现流式响应
        response = StreamingHttpResponse(stream_generator(user_input), content_type='text/event-stream')
        response['Cache-Control'] = 'no-cache'
        return response

    except json.JSONDecodeError:
        return StreamingHttpResponse("Invalid JSON", status=400)