"""Alerts Advisor — Spec 029."""
from __future__ import annotations
import os, urllib.request
from app import mail_notify

NTFY = os.getenv("DESK_OPS_NTFY_TOPIC", os.getenv("AGENTIC_NTFY_TOPIC", ""))
ROOT = os.getenv("DESK_ROOT_NOTIFY_EMAIL", "admin@ligbox.com.br")

def notify_finding(finding: dict) -> bool:
    if finding.get("severity") not in ("high", "critical"):
        return False
    title = finding.get("title", "Agentic")
    body = finding.get("suggested_human_action") or finding.get("detail_md", "")
    if NTFY:
        try:
            req = urllib.request.Request(
                f"https://ntfy.sh/{NTFY}", data=f"[Agentic] {title}\n{body}".encode(),
                method="POST", headers={"Title": f"Agentic — {title}", "Priority": "high"},
            )
            urllib.request.urlopen(req, timeout=8)
        except Exception:
            pass
    mail_notify.send_email(ROOT, f"[Ligbox Agentic] {title}", f"{body}\n— VM122")
    return True
