# rcgram/core.py
import httpx
import asyncio

class Config:
    """Configuration settings for the bot."""
    def __init__(self):
        self.echo = False  # If True, the bot will echo any received message


class TelegramPrinter:
    """
    Main class for interacting with Telegram Bot API.
    Provides synchronous-like message sending via property setter
    and an asynchronous polling loop.
    """
    def __init__(self):
        self.token = None          # Bot token from @BotFather
        self.admin_id = None        # Your personal chat ID (recipient for outgoing messages)
        self.config = Config()      # Configuration object
        self._last_update_id = 0    # Last processed update ID for polling
        self._client = httpx.AsyncClient(timeout=10)  # Shared HTTP client

    @property
    def tobot(self):
        """Property getter – just a reminder on how to use it."""
        return "Use: rcgram.tobot = 'message'"

    @tobot.setter
    def tobot(self, message):
        """
        Send a message without blocking the main thread.
        If an asyncio event loop is already running, the send is scheduled as a task;
        otherwise a new loop is started.
        """
        if not self.token or not self.admin_id:
            print(f"[rcgram] Error: token and admin_id must be set! Message: {message}")
            return

        try:
            # Check if there is a running event loop
            loop = asyncio.get_running_loop()
            loop.create_task(self._send_msg(self.admin_id, str(message)))
        except RuntimeError:
            # No running loop – run the coroutine in a new event loop
            asyncio.run(self._send_msg(self.admin_id, str(message)))

    async def _send_msg(self, chat_id: int, text: str):
        """
        Internal method to send a text message via Telegram Bot API.
        """
        url = f"https://api.telegram.org/bot{self.token}/sendMessage"
        try:
            await self._client.post(url, json={"chat_id": chat_id, "text": text})
        except Exception as e:
            print(f"[rcgram] Send error: {e}")

    async def start_polling(self):
        """
        Start an infinite polling loop that listens for incoming messages.
        If config.echo is True, it replies to any text message with the same text.
        """
        if not self.token:
            print("[rcgram] Error: token is required for polling!")
            return

        print(f"[rcgram] Async bot started (echo={self.config.echo})...")
        while True:
            if not self.config.echo:
                # If echo is disabled, just sleep and do nothing
                await asyncio.sleep(1)
                continue

            url = f"https://api.telegram.org/bot{self.token}/getUpdates"
            try:
                resp = await self._client.get(
                    url, params={"offset": self._last_update_id + 1}
                )
                data = resp.json()
                if data.get("ok"):
                    for update in data.get("result", []):
                        self._last_update_id = update["update_id"]
                        if "message" in update and "text" in update["message"]:
                            # Echo the received text back to the sender
                            await self._send_msg(
                                update["message"]["chat"]["id"],
                                update["message"]["text"]
                            )
            except Exception as e:
                print(f"[rcgram] Polling error: {e}")
            await asyncio.sleep(0.5)


# Create a singleton instance for easy import
bot_instance = TelegramPrinter()