"""macOS notifications. Uses terminal-notifier if installed, else osascript."""
import shutil
import subprocess


def _escape_applescript(s: str) -> str:
    return s.replace("\\", "\\\\").replace('"', '\\"')


def notify(*, title: str, subtitle: str, body: str, open_path: str | None = None) -> None:
    tn = shutil.which("terminal-notifier")
    if tn:
        cmd = [tn, "-title", title, "-subtitle", subtitle, "-message", body]
        if open_path:
            cmd += ["-open", f"file://{open_path}"]
        subprocess.run(cmd, check=False)
        return

    script = (
        f'display notification "{_escape_applescript(body)}" '
        f'with title "{_escape_applescript(title)}" '
        f'subtitle "{_escape_applescript(subtitle)}"'
    )
    subprocess.run(["osascript", "-e", script], check=False)
