"""NotificationCommand entity — Resolve and Execute behaviors."""
from __future__ import annotations

import enum
from dataclasses import dataclass, field
from typing import Optional

from horn.tts.base import TTSEngine, TTSTimeoutError, TTSUnavailableError


class NotificationType(enum.Enum):
    VERIFY = "verify"
    START = "start"
    DONE = "done"
    CONFIRM = "confirm"


_DEFAULT_TEXTS: dict[NotificationType, str] = {
    NotificationType.VERIFY: "Horn 已就绪，等待任务通知",
    NotificationType.START: "老板，我开始执行任务了",
    NotificationType.DONE: "老板，任务已完成",
    NotificationType.CONFIRM: "老板，有事情需要你确认",
}


class ResolveError(Exception):
    """Raised when argument combination is invalid during Resolve."""


@dataclass
class NotificationCommand:
    notification_type: NotificationType
    message: str
    resolved_text: str
    success: bool = field(default=False, init=False)
    error_message: str = field(default="", init=False)

    @classmethod
    def resolve(
        cls,
        notification_type: Optional[str],
        message: Optional[str],
    ) -> "NotificationCommand":
        """Build a NotificationCommand from raw CLI inputs.

        resolved_text priority (high → low):
          1. --message argument (if non-empty after strip)  [v1.1.0+]
          2. Default text for the resolved type
        """
        norm_message = (message or "").strip()

        if notification_type is None:
            ntype = NotificationType.VERIFY
        else:
            ntype = NotificationType(notification_type)

        resolved = norm_message if norm_message else _DEFAULT_TEXTS[ntype]

        return cls(
            notification_type=ntype,
            message=norm_message,
            resolved_text=resolved,
        )

    def execute(self, tts_engine: TTSEngine) -> None:
        """Speak resolved_text via the TTS engine; record result."""
        try:
            tts_engine.speak(self.resolved_text)
            self.success = True
        except TTSUnavailableError:
            self.success = False
            self.error_message = "[Horn] TTS 引擎不可用，请检查 Windows 语音服务是否已启用"
        except TTSTimeoutError:
            self.success = False
            self.error_message = "[Horn] 播报超时，已强制终止"
