"""macOS notification helper -- shared by mugi_runner and cron_scheduler."""

from __future__ import annotations

import logging
import subprocess

_log = logging.getLogger(__name__)


def send_mac_notification(
    title: str,
    subtitle: str,
    body: str,
    sound: bool = True,
    timeout: int = 15,
) -> bool:
    """
    Send a native macOS banner notification.  No elevated privileges.
    Tries mac_notifications first; on ImportError or any exception uses osascript.
    """
    body_safe = (body or "")[:500].replace("\n", " ")
    title_safe = (title or "Mugi")[:100]
    subtitle_safe = (subtitle or "Background Check")[:100]
    try:
        from mac_notifications import client as mac_client

        kwargs: dict = {"title": title_safe, "subtitle": subtitle_safe}
        if body_safe:
            kwargs["text"] = body_safe
        if sound:
            kwargs["sound"] = "default"
        mac_client.create_notification(**kwargs)
        _log.info(
            "Notification sent via mac_notifications: title=%s subtitle=%s preview=%s",
            title_safe,
            subtitle_safe,
            body_safe[:80],
        )
        return True
    except ImportError:
        _log.debug("mac_notifications not available, using osascript fallback")
    except Exception as e:
        _log.warning("mac_notifications failed: %s", e)

    try:
        body_esc = body_safe.replace("\\", "\\\\").replace('"', '\\"').replace("\r", " ").replace("\n", " ")
        title_esc = title_safe.replace("\\", "\\\\").replace('"', '\\"')
        sub_esc = subtitle_safe.replace("\\", "\\\\").replace('"', '\\"')
        script = f'display notification "{body_esc}" with title "{title_esc}" subtitle "{sub_esc}"'
        if sound:
            script += ' sound name "default"'
        subprocess.run(["osascript", "-e", script], check=True, timeout=10, capture_output=True)
        _log.info(
            "Notification sent via osascript: title=%s subtitle=%s preview=%s",
            title_safe,
            subtitle_safe,
            body_safe[:80],
        )
        return True
    except subprocess.TimeoutExpired:
        _log.warning("Notification osascript timeout")
        return False
    except Exception as e:
        _log.warning("Notification osascript failed: %s", e)
        return False
