#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：django_base_ai
@File    ：wanxiang.py
@Desc    ：通义万相（阿里云 DashScope）文生图封装
"""

import logging
from typing import Any

logger = logging.getLogger(__name__)

# 默认模型：通用快速；可选 wanx2.0-t2i-turbo / wanx2.1-t2i-plus
DEFAULT_MODEL = "wanx2.1-t2i-turbo"
DEFAULT_SIZE = "1024*1024"


def generate_image(
    prompt: str,
    api_key: str | None = None,
    model: str | None = None,
    n: int = 1,
    size: str | None = None,
) -> tuple[list[str], str | None]:
    """
    调用通义万相文生图，返回图片 URL 列表与错误信息。
    :param prompt: 英文或中文提示词（建议英文效果更稳）
    :param api_key: 不传则从 Django settings 读取 AI_WANXIANG_API_KEY
    :param model: 如 wanx2.1-t2i-turbo、wanx2.0-t2i-turbo
    :param n: 生成张数 1–4
    :param size: 如 1024*1024
    :return: (urls, error)，成功时 error 为 None；失败时 urls 为空、error 为错误说明
    """
    try:
        from django.conf import settings

        key = api_key or getattr(settings, "AI_WANXIANG_API_KEY", None) or ""
        if not key:
            return [], "未配置 AI_WANXIANG_API_KEY，请在 conf/env.py 或 conf/pro.py 中设置"

        from dashscope import ImageSynthesis

        model = model or getattr(settings, "AI_WANXIANG_DEFAULT_MODEL", None) or DEFAULT_MODEL
        size = size or DEFAULT_SIZE
        n = max(1, min(4, int(n)))

        rsp = ImageSynthesis.call(
            api_key=key,
            model=model,
            prompt=prompt,
            n=n,
            size=size,
        )
    except ImportError as e:
        logger.warning("dashscope 未安装: %s，请执行 pip install dashscope", e)
        return [], "未安装 dashscope，请执行 pip install dashscope"
    except Exception as e:
        err_msg = str(e)
        logger.exception("通义万相文生图失败: %s", e)
        # 未开通/无权限（AccessDenied.Unpurchased）时给出明确指引
        if "Unpurchased" in err_msg or "Access to model denied" in err_msg or "AccessDenied" in err_msg:
            return [], (
                "通义万相未开通或当前模型无权限。请登录阿里云百炼 (https://www.aliyun.com/product/bailian) "
                "开通「万相」文生图并领取免费额度；若已开通仍报错，可在 conf 中设置 AI_WANXIANG_DEFAULT_MODEL 为 wanx2.0-t2i-turbo 再试。"
            )
        return [], err_msg

    urls: list[str] = []
    if getattr(rsp, "output", None) and getattr(rsp.output, "results", None):
        for r in rsp.output.results:
            if getattr(r, "url", None):
                urls.append(r.url)
    if not urls and getattr(rsp, "message", None):
        return [], rsp.message or "API 未返回图片"
    if not urls:
        return [], "API 返回无图片 URL"
    return urls, None


def get_wanxiang_config() -> dict[str, Any]:
    """从 Django settings 读取通义万相配置（供前端或其它模块判断是否可用）。"""
    try:
        from django.conf import settings

        return {
            "api_key_configured": bool(getattr(settings, "AI_WANXIANG_API_KEY", None)),
            "default_model": getattr(settings, "AI_WANXIANG_DEFAULT_MODEL", None) or DEFAULT_MODEL,
        }
    except Exception:
        return {"api_key_configured": False, "default_model": DEFAULT_MODEL}
