"""Notification helpers — ntfy and SMTP via Proton Bridge."""

import logging
import smtplib
import ssl
import urllib.request
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

log = logging.getLogger(__name__)

SMTP_HOST = "127.0.0.1"
SMTP_PORT = 1025
SMTP_USER = "admin@thevish.io"
SMTP_PASS = "REDACTED_PASSWORD"  # pragma: allowlist secret
DEFAULT_TO = "admin@thevish.io"


def send_ntfy(topic: str, title: str, message: str, priority: str = "default",
              base_url: str = "https://ntfy.sh"):
    """Send a push notification via ntfy."""
    url = f"{base_url.rstrip('/')}/{topic}"
    try:
        req = urllib.request.Request(url, data=message.encode(), headers={
            "Title": title,
            "Priority": priority,
            "Content-Type": "text/plain",
        })
        with urllib.request.urlopen(req, timeout=10):
            pass
        log.info("ntfy sent: %s", title)
    except Exception as e:
        log.warning("ntfy failed: %s", e)


def send_email(subject: str, html_body: str = "", text_body: str = "",
               to: str = DEFAULT_TO, from_addr: str = SMTP_USER):
    """Send email via Proton Bridge SMTP on localhost."""
    msg = MIMEMultipart("alternative")
    msg["Subject"] = subject
    msg["From"] = from_addr
    msg["To"] = to

    if text_body:
        msg.attach(MIMEText(text_body, "plain"))
    if html_body:
        msg.attach(MIMEText(html_body, "html"))

    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE

    with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server:
        server.starttls(context=ctx)
        server.login(SMTP_USER, SMTP_PASS)
        server.send_message(msg)

    log.info("Email sent: %s -> %s", subject, to)
