import logging

from django.conf import settings

logger = logging.getLogger(__name__)


def enqueue_mission_created_speech(*, mission) -> None:
    if not getattr(settings, "SPEECH_ENABLED", True):
        return
    if not getattr(settings, "MISSION_SPEECH_NOTIFY_ENABLED", True):
        return

    category = getattr(mission, "category", None)
    if not getattr(category, "speech_enabled", False):
        return

    text = _build_mission_created_speech_text(mission=mission)
    try:
        from mission.tasks import notify_mission_speech

        notify_mission_speech.delay(text=text)
    except Exception:
        logger.exception("[mission.notifications] 投递任务语音播报任务失败（已忽略）")


def _build_mission_created_speech_text(*, mission) -> str:
    category_name = getattr(getattr(mission, "category", None), "name", "任务") or "任务"
    creator_name = getattr(getattr(mission, "creator", None), "name", "") or ""
    prefix = f"{creator_name}创建了" if creator_name else "创建了"
    description = (getattr(mission, "description", "") or "").strip()
    if len(description) > 60:
        description = f"{description[:60]}..."
    if description:
        return f"{prefix}{category_name}任务，{description}"
    return f"{prefix}{category_name}任务"
