"""
AllPredictor Monétisation SDK — Python
======================================
Intégrez ce fichier dans votre bot Telegram pour activer :
  - L'affichage automatique de publicités
  - Le comptage d'utilisateurs uniques
  - Les crédits publisher automatiques (300 F / diffusion)

Prérequis :
  pip install aiohttp

Configuration Cloudflare : ajoutez l'URL du webhook GeniusPay
dans votre dashboard GeniusPay → https://allpredictor.com/api/monetize-webhook

Utilisation rapide (python-telegram-bot v20+) :
------------------------------------------------
    from allpredictor_monetize import AllPredictorMonetize

    mnt = AllPredictorMonetize(
        api_key = "ap_votre_clé_api",
        bot_id  = "VOTRE_BOT_ID",     # trouvez-le dans Dashboard > Bots
    )

    async def start(update, context):
        ad  = await mnt.get_ad(user_id=update.effective_user.id)
        msg = "Bienvenue ! 🎯\\n\\nVoici votre prédiction..."
        msg += mnt.format_ad(ad)
        await update.message.reply_text(msg, parse_mode="HTML")

    async def predict(update, context):
        ad  = await mnt.get_ad(user_id=update.effective_user.id)
        msg = "📊 Prédiction : 2.45x"
        msg += mnt.format_ad(ad)
        await update.message.reply_text(msg, parse_mode="HTML")
"""

import random
import logging
from typing import Optional

try:
    import aiohttp
    _AIOHTTP = True
except ImportError:
    _AIOHTTP = False
    try:
        import urllib.request, json as _json
    except ImportError:
        pass

logger = logging.getLogger(__name__)

BASE_URL = "https://allpredictor.com/api/v1"


class AllPredictorMonetize:
    """Client de monétisation AllPredictor pour bots Telegram (async)."""

    def __init__(self, api_key: str, bot_id: str, show_ads: bool = True):
        """
        :param api_key:  Votre clé API AllPredictor (x-api-key)
        :param bot_id:   L'identifiant de votre bot dans AllPredictor
        :param show_ads: Mettre à False pour désactiver les pubs sans supprimer le code
        """
        if not api_key or not bot_id:
            raise ValueError("api_key et bot_id sont requis.")
        self.api_key  = api_key
        self.bot_id   = bot_id
        self.show_ads = show_ads
        self._session = None


    def _get_session(self):
        if not _AIOHTTP:
            return None
        if self._session is None or self._session.closed:
            self._session = aiohttp.ClientSession(
                headers={"X-API-Key": self.api_key},
                timeout=aiohttp.ClientTimeout(total=5),
            )
        return self._session

    async def close(self):
        """Fermer la session HTTP. Appelez en fin de programme."""
        if self._session and not self._session.closed:
            await self._session.close()


    async def get_ad(self, user_id: Optional[int] = None) -> Optional[dict]:
        """
        Récupère une publicité à afficher et enregistre l'impression.

        :param user_id: ID Telegram de l'utilisateur (pour comptage unique)
        :return: dict avec les clés {id, type, content, url} ou None
        """
        if not self.show_ads:
            return None

        params = {"botId": self.bot_id}
        if user_id is not None:
            params["userId"] = str(user_id)

        try:
            if _AIOHTTP:
                async with self._get_session().get(
                    f"{BASE_URL}/monetize/serve",
                    params=params,
                ) as resp:
                    if resp.status == 200:
                        data = await resp.json()
                        return data.get("ad") if data.get("success") else None
            else:
                import urllib.request, json as _json
                url = f"{BASE_URL}/monetize/serve?" + "&".join(f"{k}={v}" for k, v in params.items())
                req = urllib.request.Request(url, headers={"X-API-Key": self.api_key})
                with urllib.request.urlopen(req, timeout=5) as r:
                    data = _json.loads(r.read())
                    return data.get("ad") if data.get("success") else None
        except Exception as e:
            logger.debug(f"AllPredictor get_ad error: {e}")
            return None


    def format_ad(self, ad: Optional[dict], separator: bool = True) -> str:
        """
        Formate une publicité en texte HTML Telegram.

        :param ad:        Dictionnaire retourné par get_ad()
        :param separator: Ajouter une ligne de séparation avant la pub
        :return: Chaîne HTML à concaténer à votre message
        """
        if not ad:
            return ""

        lines = []
        if separator:
            lines.append("\n\n<b>─────────────────</b>")

        ad_type  = ad.get("type", "texte")
        content  = ad.get("content", "")
        url      = ad.get("url", "")

        if ad_type in ("texte", "emoji"):
            lines.append(f"📢 {content}")
        elif ad_type == "lien":
            lines.append(f"🔗 <b>{content}</b>")
            if url:
                lines.append(f'👉 <a href="{url}">Cliquez ici</a>')
        elif ad_type == "image":
            lines.append(f"🖼 {content}")
            if url:
                lines.append(f'👉 <a href="{url}">Voir plus</a>')
        elif ad_type in ("musique", "audio"):
            lines.append(f"🎵 {content}")
        elif ad_type == "video":
            lines.append(f"🎬 {content}")
            if url:
                lines.append(f'👉 <a href="{url}">Regarder</a>')
        elif ad_type == "icone":
            lines.append(content)
        else:
            lines.append(f"📢 {content}")

        lines.append("<i>Pub AllPredictor</i>")
        return "\n".join(lines)


    async def append_ad(self, message: str, user_id: Optional[int] = None) -> str:
        """
        Raccourci qui concatène directement la pub à un message.

        Usage :
            text = await mnt.append_ad("Votre prédiction : 2.45x", user_id=123)
            await update.message.reply_text(text, parse_mode="HTML")
        """
        ad = await self.get_ad(user_id=user_id)
        return message + self.format_ad(ad)
