import asyncio
import websockets
import json

class BotClient:
    def __init__(self, token, ws_url="wss://chat.talkky.shop/ws"):
        self.token = token
        self.ws_url = f"{ws_url}?bot_token={token}"
        self.event_handler = None
        self.ws = None
        self.connected = False

    # ---------------------------
    # Registrar callback
    # ---------------------------
    def on_message(self, func):
        self.event_handler = func
        return func

    # ---------------------------
    # Enviar mensagem para o servidor
    # ---------------------------
    async def send_message_async(self, conversation_id, text):
        if not self.connected:
            raise Exception("Bot não conectado ainda!")
        
        payload = {
            "event": "bot_send",
            "conversation_id": conversation_id,
            "text": text
        }

        await self.ws.send(json.dumps(payload))

    def send_message(self, conversation_id, text):
        asyncio.create_task(self.send_message_async(conversation_id, text))

    # ---------------------------
    # Loop principal
    # ---------------------------
    async def connect(self):
        print("🔌 Conectando ao servidor...")
        self.ws = await websockets.connect(self.ws_url)
        self.connected = True
        print("✅ Bot conectado!")

        try:
            async for message in self.ws:
                data = json.loads(message)

                # Somente eventos que importam o bot recebe
                if data.get("event") == "new_message":
                    
                    if self.event_handler:
                        await asyncio.to_thread(self.event_handler, data)

        except websockets.exceptions.ConnectionClosed:
            print("❌ Conexão caiu, tentando reconectar...")
            self.connected = False
            await self.connect()

    def run(self):
        asyncio.run(self.connect())
