"""Standalone Lauther plugin for Apprise — no upstream install needed.

Use this TODAY with any Apprise >= 1.0 via a custom plugin directory:

    apprise --plugin-path /path/to/this/folder \
        -t "Title" -b "Body" lauther://lpt_YOURTOKEN

or drop it into ~/.apprise/plugins/ (Linux/macOS) /
%APPDATA%/Apprise/plugins (Windows), where Apprise auto-loads it.

Tools that embed Apprise with custom-plugin support pick it up the same way.
Syntax:  lauther://lpt_TOKEN  (optional: ?priority=-2..2)
"""

import json
from urllib import request as _request

from apprise.decorators import notify

LAUTHER_API = (
    "https://api.lauther.id/v1/push"
)


@notify(on="lauther")
def lauther_notification(body, title, notify_type, meta, *args, **kwargs):
    """Send a notification through Lauther."""
    token = meta.get("host", "")
    if not token.startswith("lpt_"):
        return False

    qsd = meta.get("qsd") or {}
    try:
        priority = max(-2, min(2, int(qsd.get("priority", 0))))
    except (TypeError, ValueError):
        priority = 0

    payload = json.dumps({
        "token": token,
        "title": title or "",
        "message": body or "",
        "priority": priority,
    }).encode("utf-8")

    req = _request.Request(
        LAUTHER_API,
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    try:
        with _request.urlopen(req, timeout=15) as r:
            return r.status == 200
    except Exception:
        return False
