import os
import json
import time
import requests
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.admin.views.decorators import staff_member_required
from dashscope import ImageSynthesis

# 硬编码 API Key (或者使用 os.getenv)
DASHSCOPE_API_KEY = "sk-ca7ca2c355ce408a809b77f8f8911700"  # 请替换为你自己的 Key


@csrf_exempt
@staff_member_required  # 只有管理员才能调用
def generate_image_api(request):
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'message': '仅支持 POST 请求'})

    try:
        data = json.loads(request.body)
        prompt = data.get('prompt', '')

        if not prompt:
            return JsonResponse({'status': 'error', 'message': '请输入图片描述'})

        # 1. 调用阿里云 DashScope
        rsp = ImageSynthesis.call(
            api_key=DASHSCOPE_API_KEY,
            model=ImageSynthesis.Models.wanx_v1,
            prompt=prompt,
            n=1,
            style='<watercolor>',  # 默认水彩风格，可根据需要修改或让前端传参
            size='1024*1024'
        )

        if rsp.status_code == HTTPStatus.OK:
            # 2. 获取图片 URL
            img_url = rsp.output.results[0].url

            # 3. 下载并保存图片到本地 media 目录
            # 确保保存目录存在
            save_dir = os.path.join(settings.MEDIA_ROOT, 'ai_generated')
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)

            # 生成文件名 (使用时间戳防止重名)
            file_name = f"ai_{int(time.time())}.png"
            local_path = os.path.join(save_dir, file_name)

            # 下载
            img_data = requests.get(img_url).content
            with open(local_path, 'wb+') as f:
                f.write(img_data)

            # 4. 返回本地访问 URL
            # 假设 MEDIA_URL 是 /media/
            local_url = f"{settings.MEDIA_URL}ai_generated/{file_name}"

            return JsonResponse({
                'status': 'success',
                'url': local_url,
                'msg': '生成成功！链接已复制'
            })
        else:
            return JsonResponse({
                'status': 'error',
                'message': f"API错误: {rsp.message}"
            })

    except Exception as e:
        return JsonResponse({'status': 'error', 'message': str(e)})