import logging

from django.conf import settings
from django.db import transaction

logger = logging.getLogger(__name__)


def enqueue_business_order_speech(*, order, order_label: str, action_label: str) -> None:
    if not getattr(settings, 'BUSINESS_ORDER_SPEECH_NOTIFY_ENABLED', True):
        return
    if _is_external_order(order):
        return

    order_id = _get_order_identifier(order)
    text = f'{order_label} {order_id} 已{action_label}'

    def _enqueue():
        try:
            from business.tasks import notify_business_order_speech

            notify_business_order_speech.delay(text=text)
        except Exception:
            logger.exception('[business.notifications] 投递业务单据语音播报任务失败（已忽略）')

    transaction.on_commit(_enqueue)


def _is_external_order(order) -> bool:
    return bool(
        getattr(order, 'is_external_source', False)
        or getattr(order, 'external_source_id', None)
    )


def _get_order_identifier(order) -> str:
    human_id = getattr(order, 'human_id', None)
    if human_id:
        return str(human_id)
    return str(getattr(order, 'id', ''))
