import json
import time
import urllib.request
import urllib.error
from importlib.metadata import version

MAX_RETRIES = 2
TIMEOUT_S = 10

try:
    _version = version("notilens")
except Exception:
    _version = "0.0.0"


def send_notification(endpoint: str, secret: str, payload: dict) -> None:
    body = json.dumps(payload).encode("utf-8")
    headers = {
        "Content-Type": "application/json",
        "X-NOTILENS-KEY": secret,
        "User-Agent": f"NotiLens-CLI/{_version}",
        "Content-Length": str(len(body)),
    }

    req = urllib.request.Request(endpoint, data=body, headers=headers, method="POST")

    last_err = None
    for i in range(MAX_RETRIES + 1):
        try:
            with urllib.request.urlopen(req, timeout=TIMEOUT_S):
                return
        except Exception as e:
            last_err = e
            if i < MAX_RETRIES:
                time.sleep(1)

    raise last_err
