from __future__ import annotations

import json
import re


def is_volume_unavailable_error(exc: BaseException) -> bool:
    """识别系统盘类型不可用或售罄导致的华为云创建失败。"""
    text = f"{exc} {getattr(exc, 'body', '')}".lower()
    return any(token in text for token in ("ecs.0044", "volumetype", "volume type", "sellout", "sell out", "sold out"))


def is_flavor_unavailable_error(exc: BaseException) -> bool:
    """识别规格不可用、售罄或下线导致的华为云创建失败。"""
    text = f"{exc} {getattr(exc, 'body', '')}".lower()
    return any(token in text for token in ("ecs.0018", "ecs.0019", "sold out", "abandoned", "flavor"))


def is_capacity_retry_error(exc: BaseException) -> bool:
    """判断华为云容量相关失败是否适合切换规格或磁盘后重试。"""
    text = f"{exc} {getattr(exc, 'body', '')}".lower()
    return any(
        token in text
        for token in (
            "ecs.0018",
            "ecs.0019",
            "ecs.0044",
            "sold out",
            "sellout",
            "sell out",
            "abandoned",
            "flavor",
            "volumetype",
            "volume type",
        )
    )


def is_instance_not_found_error(exc: BaseException) -> bool:
    """识别云服务器不存在或 ID 已失效的华为云接口错误。"""
    text = str(exc).lower()
    body = str(getattr(exc, "body", "") or "").lower()
    combined = f"{text} {body}"
    return any(token in combined for token in ("ecs.0614", "could not be found", "instance["))


def cloud_error_message_cn(exc: BaseException) -> str:
    """把常见华为云接口异常转换成界面可读的中文提示。"""
    text = str(exc)
    body = str(getattr(exc, "body", "") or "")
    status = getattr(exc, "status", None)
    code = ""
    message = ""
    payload = body or text
    try:
        parsed = json.loads(payload)
        if isinstance(parsed, dict):
            error = parsed.get("error") if isinstance(parsed.get("error"), dict) else parsed
            code = str(error.get("code") or error.get("error_code") or parsed.get("error_code") or "")
            message = str(error.get("message") or error.get("error_msg") or parsed.get("error_msg") or "")
    except Exception:
        code_match = re.search(r'"(?:code|error_code)"\s*:\s*"([^"]+)"', payload)
        msg_match = re.search(r'"(?:message|error_msg)"\s*:\s*"([^"]+)"', payload)
        if code_match:
            code = code_match.group(1)
        if msg_match:
            message = msg_match.group(1)
    lower = f"{code} {message} {text} {body}".lower()
    if "ecs.0614" in lower or "could not be found" in lower:
        cn = "云服务器不存在或ID已失效，程序会重新读取当前地区云服务器后再处理。"
    elif "pending_payment" in lower or "待支付" in lower:
        cn = "订单处于待支付状态，请确认余额或手动支付。"
    elif "sold out" in lower or "sellout" in lower or "售罄" in lower:
        cn = "当前规格或资源售罄，程序会尝试候选规格/磁盘或下一可用资源。"
    elif status:
        cn = f"华为云接口返回 HTTP {status}。"
    else:
        cn = "云接口返回异常。"
    detail = message or text
    if code:
        return f"华为云错误 {code}：{cn}原始提示：{detail}"
    if status:
        return f"华为云HTTP {status}：{cn}原始提示：{detail}"
    return text
