from __future__ import annotations

import shutil
import subprocess


def send_message(target: str | None, message: str) -> None:
    """
    Unified message sending entrypoint.

    - If `openclaw` CLI is available, send via OpenClaw (best-effort).
    - Otherwise, print to stdout (best-effort).
    """

    # No target: fall back to stdout
    if not target:
        print(str(message), flush=True)
        return

    try:
        if shutil.which("openclaw"):
            send_openclaw_message(str(target), str(message))
            return
    except Exception:
        # fall back below
        pass

    print(str(message), flush=True)


def send_openclaw_message(target: str, message: str) -> None:
    """
    Send notification via:
      openclaw message send --target xxxx --message "..."

    This is a best-effort helper: any failure is swallowed (no stdout/stderr spam).
    """
    cmd = ["openclaw", "message", "send", "--target", str(target), "--message", str(message)]
    try:
        subprocess.run(cmd, check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    except Exception:
        pass

