"""تنبيهات واتساب عبر Evolution API (خادم ذاتي الاستضافة).

الإعداد بمتغيرات البيئة:
  EVOLUTION_URL      مثال: http://localhost:8080
  EVOLUTION_APIKEY   مفتاح الـ API (هيدر apikey)
  EVOLUTION_INSTANCE اسم الـ instance المتصل بواتساب

بدون هذه المتغيرات تعمل الدالات كـ no-op (تطوير/اختبار).
ملاحظة إنتاج: Evolution API غير رسمي (بروتوكول واتساب ويب) — ممتاز للـ MVP
وخطر حظر الرقم وارد؛ عند التوسع البديل الرسمي Unifonic/WhatsApp Cloud API.
"""

import base64
import re

import httpx

import os


def _cfg():
    url = os.environ.get("EVOLUTION_URL", "").rstrip("/")
    key = os.environ.get("EVOLUTION_APIKEY", "")
    instance = os.environ.get("EVOLUTION_INSTANCE", "")
    return (url, key, instance) if url and key and instance else None


def normalize(number: str) -> str:
    """966 55 000-0000 → 966550000000 (صيغة دولية بلا +)."""
    return re.sub(r"\D", "", number)


def _post(path: str, payload: dict) -> bool:
    cfg = _cfg()
    if not cfg:
        return False
    url, key, instance = cfg
    try:
        r = httpx.post(f"{url}/{path}/{instance}", json=payload,
                       headers={"apikey": key}, timeout=20)
        if r.status_code >= 300:
            print(f"[notifier] evolution {path} failed {r.status_code}: {r.text[:200]}",
                  flush=True)
        return r.status_code < 300
    except Exception as exc:
        print(f"[notifier] evolution error: {exc}", flush=True)
        return False


def send_text(number: str, text: str) -> bool:
    return _post("message/sendText", {"number": normalize(number), "text": text})


def send_image(number: str, caption: str, image_bytes: bytes) -> bool:
    return _post("message/sendMedia", {
        "number": normalize(number),
        "mediatype": "image",
        "mimetype": "image/jpeg",
        "fileName": "veedon-alert.jpg",
        "caption": caption,
        "media": base64.standard_b64encode(image_bytes).decode(),
    })


def _channels(text: str, image: bytes | None = None) -> None:
    """بثّ للقنوات المُهيّأة بجانب واتساب (Telegram/Slack/Teams/Webhook) — no-op إن لم تُضبط."""
    tok, chat = os.environ.get("TELEGRAM_BOT_TOKEN"), os.environ.get("TELEGRAM_CHAT_ID")
    if tok and chat:
        try:
            if image:
                httpx.post(f"https://api.telegram.org/bot{tok}/sendPhoto",
                           data={"chat_id": chat, "caption": text[:1024]},
                           files={"photo": ("a.jpg", image, "image/jpeg")}, timeout=20)
            else:
                httpx.post(f"https://api.telegram.org/bot{tok}/sendMessage",
                           json={"chat_id": chat, "text": text}, timeout=20)
        except Exception as exc:
            print(f"[notifier] telegram error: {exc}", flush=True)
    for env in ("SLACK_WEBHOOK_URL", "TEAMS_WEBHOOK_URL", "VEEDON_WEBHOOK_URL"):
        u = os.environ.get(env)
        if u:
            try:                                   # Slack/Teams/عام يقبلون {"text": …}
                httpx.post(u, json={"text": text}, timeout=20)
            except Exception as exc:
                print(f"[notifier] {env} error: {exc}", flush=True)


def send_alert(numbers: str, text: str, snapshot_path: str | None = None) -> int:
    """يرسل لكل الأرقام (واتساب) + القنوات المُهيّأة. يرجع عدد إرسالات واتساب الناجحة."""
    image = None
    if snapshot_path and os.path.isfile(snapshot_path):
        with open(snapshot_path, "rb") as f:
            image = f.read()
    sent = 0
    for number in [n for n in (numbers or "").split(",") if n.strip()]:
        ok = (send_image(number, text, image) if image
              else send_text(number, text))
        sent += 1 if ok else 0
    _channels(text, image)                         # Telegram/Slack/Teams/Webhook
    return sent
