"""CLI entry point — argument parsing, error output, and process exit codes."""
from __future__ import annotations

import sys
from typing import Optional

from horn.notify import NotificationCommand, ResolveError
from horn.tts.base import TTSEngine, TTSUnavailableError


def _stderr(message: str) -> None:
    print(message, file=sys.stderr)


def _parse_args(argv: list[str]) -> Optional[str]:
    """Return notification_type from raw argv (excluding program name).

    Returns None for bare command (verify). Raises SystemExit(1) on invalid input.
    """
    type_flags = {"--start": "start", "--done": "done", "--confirm": "confirm"}
    notification_type: Optional[str] = None
    for arg in argv:
        if arg in type_flags:
            if notification_type is not None:
                _stderr("[Horn] 不能同时指定多个通知类型")
                sys.exit(1)
            notification_type = type_flags[arg]
        else:
            _stderr("[Horn] 未知参数，请使用 horn --start / --done / --confirm")
            sys.exit(1)
    return notification_type


def main() -> None:
    notification_type = _parse_args(sys.argv[1:])

    try:
        cmd = NotificationCommand.resolve(
            notification_type=notification_type,
            message=None,
        )
    except ResolveError as exc:
        _stderr(str(exc))
        sys.exit(1)

    try:
        tts = TTSEngine()
    except TTSUnavailableError:
        _stderr("[Horn] TTS 引擎不可用，请检查 Windows 语音服务是否已启用")
        sys.exit(1)

    cmd.execute(tts)

    if not cmd.success:
        _stderr(cmd.error_message)
        sys.exit(1)

    sys.exit(0)
