import asyncio
import random
import logging
from database import log_system_event

logger = logging.getLogger("ServicesEngine")

class TelegramServicesEngine:
    def __init__(self, user_clients_dict: dict):
        self.user_clients = user_clients_dict # account_id -> Pyrogram Client

    async def boost_post_views(self, chat_identifier: str, message_ids: list):
        """Boost Telegram Channel Post Views using all loaded accounts"""
        if not self.user_clients:
            return False, "No active userbot accounts loaded"

        success_count = 0
        log_system_event(f"Starting Post View Booster on {chat_identifier} for posts {message_ids} with {len(self.user_clients)} accounts...")

        for acc_id, client in self.user_clients.items():
            try:
                chat = await client.get_chat(chat_identifier)
                # Fetching messages acknowledges views on Telegram servers
                await client.get_messages(chat.id, message_ids)
                success_count += 1
                await asyncio.sleep(random.uniform(0.1, 0.4))
            except Exception as e:
                logger.error(f"View booster error on acc #{acc_id}: {e}")

        msg = f"👁️ Views Boosted! {success_count}/{len(self.user_clients)} accounts viewed post(s) in {chat_identifier}."
        log_system_event(msg)
        return True, msg

    async def vote_on_poll(self, chat_identifier: str, message_id: int, option_index: int):
        """Mass vote on a Telegram Poll using all loaded accounts"""
        if not self.user_clients:
            return False, "No active userbot accounts loaded"

        success_count = 0
        log_system_event(f"Starting Poll Voting on {chat_identifier} message #{message_id} option #{option_index}...")

        for acc_id, client in self.user_clients.items():
            try:
                chat = await client.get_chat(chat_identifier)
                await client.vote_poll(chat.id, message_id, [option_index])
                success_count += 1
                await asyncio.sleep(random.uniform(0.2, 0.6))
            except Exception as e:
                logger.error(f"Poll vote error on acc #{acc_id}: {e}")

        msg = f"📊 Poll Vote Service: Successfully voted with {success_count}/{len(self.user_clients)} accounts on option #{option_index}!"
        log_system_event(msg)
        return True, msg

    async def mass_join_chat(self, chat_identifier: str):
        """Make all loaded accounts join a client's Telegram Channel or Group"""
        if not self.user_clients:
            return False, "No active userbot accounts loaded"

        success_count = 0
        log_system_event(f"Starting Mass Channel Join on {chat_identifier} with {len(self.user_clients)} accounts...")

        for acc_id, client in self.user_clients.items():
            try:
                await client.join_chat(chat_identifier)
                success_count += 1
                await asyncio.sleep(random.uniform(0.5, 1.2))
            except Exception as e:
                logger.error(f"Mass join error on acc #{acc_id}: {e}")

        msg = f"🚀 Mass Join Service: {success_count}/{len(self.user_clients)} accounts successfully joined {chat_identifier}!"
        log_system_event(msg)
        return True, msg

    async def send_live_comments(self, chat_identifier: str, custom_comments: list, delay_range: tuple = (1.5, 4.0)):
        """Send custom live comments into TG Live / Group chat using accounts"""
        if not self.user_clients or not custom_comments:
            return False, "No accounts loaded or empty comments list"

        sent_count = 0
        log_system_event(f"Sending live comments to {chat_identifier} using {len(self.user_clients)} accounts...")

        for acc_id, client in self.user_clients.items():
            try:
                comment_text = random.choice(custom_comments)
                chat = await client.get_chat(chat_identifier)
                await client.send_message(chat.id, comment_text)
                sent_count += 1
                await asyncio.sleep(random.uniform(delay_range[0], delay_range[1]))
            except Exception as e:
                logger.error(f"Live comment error on acc #{acc_id}: {e}")

        msg = f"💬 Live Commenter: Sent {sent_count} live comments into {chat_identifier}!"
        log_system_event(msg)
        return True, msg
