"""
使用:
    from enconia_utils import Credentials, send_mns_message
    
    Credentials.init(access_key_id="xxx", access_key_secret="xxx")
    
    send_mns_message("queue_name", {"key": "value"})
"""

import json
import logging
from typing import Union
import mns.account as mns_account
import mns.queue as mns_queue

logger = logging.getLogger(__name__)


def send_mns_message(queue_name: str, message_body: Union[dict, list, str]) -> bool:
    from .credentials import Credentials
    ak_id, ak_secret, endpoint = Credentials.get_mns_config()
    account = mns_account.Account(endpoint, ak_id, ak_secret)
    queue = account.get_queue(queue_name)
    msg = mns_queue.Message()
    if isinstance(message_body, (dict, list)):
        body_str = json.dumps(message_body, ensure_ascii=False)
    else:
        body_str = str(message_body)
    msg.message_body = body_str
    try:
        queue.send_message(msg)
        logger.info(f"MNS消息发送成功: queue={queue_name}")
        return True
    except Exception as e:
        logger.error(f"MNS消息发送失败: queue={queue_name}, error={str(e)}")
        return False
