"""
Fournisseurs de notifications :
- Telegram Bot API (gratuit, illimite)
- Gmail SMTP (gratuit, 500 emails/jour)
- Discord Webhook (gratuit, illimite)
"""
import smtplib
import requests
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


# ── Telegram ──────────────────────────────────────────────────────────────────

def send_telegram(token: str, chat_ids: list, message: str) -> dict:
    """
    Envoie un message Telegram a plusieurs chat_id.
    Retourne {chat_id: succes_bool}.
    """
    results = {}
    url = f"https://api.telegram.org/bot{token}/sendMessage"

    for chat_id in chat_ids:
        try:
            resp = requests.post(
                url,
                json={"chat_id": chat_id, "text": message, "parse_mode": "HTML"},
                timeout=10,
            )
            results[chat_id] = resp.status_code == 200 and resp.json().get("ok")
        except Exception as e:
            print(f"  Erreur Telegram ({chat_id}): {e}")
            results[chat_id] = False

    return results


def get_telegram_chat_id(token: str) -> str | None:
    """
    Recupere le chat_id du dernier message recu par le bot.
    Utile pour que l'utilisateur trouve son chat_id facilement.
    """
    try:
        resp = requests.get(
            f"https://api.telegram.org/bot{token}/getUpdates",
            timeout=10,
        )
        data = resp.json()
        updates = data.get("result", [])
        if updates:
            return str(updates[-1]["message"]["chat"]["id"])
    except Exception:
        pass
    return None


# ── Gmail SMTP ────────────────────────────────────────────────────────────────

def send_gmail(gmail_address: str, app_password: str,
               recipients: list, subject: str, message: str) -> dict:
    """
    Envoie un email via Gmail SMTP (mot de passe d'application requis).
    Retourne {email: succes_bool}.
    """
    results = {}

    try:
        server = smtplib.SMTP_SSL("smtp.gmail.com", 465, timeout=15)
        server.login(gmail_address, app_password)

        for recipient in recipients:
            try:
                msg = MIMEMultipart("alternative")
                msg["Subject"] = subject
                msg["From"] = gmail_address
                msg["To"] = recipient
                msg.attach(MIMEText(message, "plain", "utf-8"))

                server.sendmail(gmail_address, recipient, msg.as_string())
                results[recipient] = True
            except Exception as e:
                print(f"  Erreur Gmail ({recipient}): {e}")
                results[recipient] = False

        server.quit()

    except smtplib.SMTPAuthenticationError:
        print("  Erreur Gmail: authentification echouee. Verifie ton mot de passe d'application.")
        results = {r: False for r in recipients}
    except Exception as e:
        print(f"  Erreur Gmail: {e}")
        results = {r: False for r in recipients}

    return results


# ── Discord Webhook ───────────────────────────────────────────────────────────

def send_discord(webhook_urls: list, message: str) -> dict:
    """
    Envoie un message via un ou plusieurs webhooks Discord.
    Retourne {webhook_url: succes_bool}.
    """
    results = {}

    for url in webhook_urls:
        try:
            resp = requests.post(
                url,
                json={"content": message},
                timeout=10,
            )
            # Discord retourne 204 No Content si succes
            results[url] = resp.status_code in (200, 204)
        except Exception as e:
            print(f"  Erreur Discord: {e}")
            results[url] = False

    return results
