"""
AKHMShare Python Library
------------------------
Universal Telegram bot mailing library.

Bot creator must provide:
- BOT_TOKEN
- API_KEY
- API_URL
- get_user_ids() function returning list or set of Telegram user IDs
"""

import threading
import time
import requests


class AKHMShare:
    TELEGRAM_API = "https://api.telegram.org/bot{token}/{method}"

    def __init__(self, bot_token, api_key, api_url, get_user_ids_func, check_interval=60):
        """
        Initialize AKHMShare mailing bot.

        :param bot_token: Telegram bot token
        :param api_key: API key for your server
        :param api_url: Server endpoint for fetching messages
        :param get_user_ids_func: Function returning list/set of Telegram user IDs
        :param check_interval: Polling interval in seconds
        """
        self.bot_token = bot_token
        self.api_key = api_key
        self.api_url = api_url
        self.check_interval = check_interval
        self.get_user_ids_func = get_user_ids_func
        self._running = False
        self._last_message_id = None

        # Validation: check if function is callable and returns list/set
        if not callable(self.get_user_ids_func):
            raise ValueError("get_user_ids_func must be a callable function")
        try:
            user_ids = self.get_user_ids_func()
            if not isinstance(user_ids, (list, set)):
                raise ValueError("get_user_ids_func must return a list or set of user IDs")
        except Exception as e:
            raise ValueError(f"get_user_ids_func raised an exception during check: {e}")

    # ---------------- PUBLIC ----------------

    def start(self):
        """
        Start background polling
        """
        if self._running:
            return
        self._running = True
        threading.Thread(target=self._poll_loop, daemon=True).start()

    def stop(self):
        """
        Stop background polling
        """
        self._running = False

    # ---------------- INTERNAL ----------------

    def _poll_loop(self):
        while self._running:
            try:
                resp = requests.post(
                    self.api_url,
                    json={
                        "api_key": self.api_key,
                        "last_message_id": self._last_message_id
                    },
                    timeout=5
                )

                if resp.status_code == 200:
                    data = resp.json()
                    if data.get("has_new"):
                        message = data.get("message")
                        if message:
                            self._handle_message(message)
            except Exception:
                pass

            time.sleep(self.check_interval)

    def _handle_message(self, message: dict):
        msg_id = message.get("id")
        text = message.get("text")

        if not text or msg_id == self._last_message_id:
            return

        self._last_message_id = msg_id

        user_ids = self._get_user_ids_safe()
        for uid in user_ids:
            self._send_message(uid, text)

    def _get_user_ids_safe(self):
        try:
            user_ids = self.get_user_ids_func()
            if isinstance(user_ids, (list, set)):
                return list(user_ids)
        except Exception:
            pass
        return []

    def _send_message(self, user_id: int, text: str):
        try:
            url = self.TELEGRAM_API.format(token=self.bot_token, method="sendMessage")
            requests.post(url, json={"chat_id": user_id, "text": text}, timeout=5)
        except Exception:
            pass

