import asyncio
import websockets
from datetime import datetime
from dataclasses import dataclass
from typing import List, Optional

@dataclass
class ChatMessage:
    timestamp: datetime
    username: str
    content: str

class TwitchChatBot:
    def __init__(self, channel: str):
        self.channel = channel.lower()
        self.messages: List[ChatMessage] = []
        self.uri = "wss://irc-ws.chat.twitch.tv:443"

    def get_last_message(self) -> Optional[ChatMessage]:
        return self.messages[-1] if self.messages else None

    def get_all_messages(self) -> List[ChatMessage]:
        return self.messages

    async def connect_to_twitch_chat(self):
        async with websockets.connect(self.uri) as websocket:
            # Se connecter en tant qu'utilisateur anonyme
            await websocket.send("CAP REQ :twitch.tv/tags twitch.tv/commands")
            await websocket.send("NICK justinfan12345")
            await websocket.send(f"JOIN #{self.channel}")

            print(f"✅ Connecté au chat de #{self.channel}")

            while True:
                try:
                    message = await websocket.recv()
                    if "PRIVMSG" in message:
                        # Extraction des données du message
                        user = message.split("!", 1)[0][1:]
                        if "display-name=" in user:
                            user = user.split("display-name=")[1].split(";")[0]
                        else:
                            user = user.lower()
                        
                        msg = message.split("PRIVMSG", 1)[1].split(":", 1)[1]
                        timestamp = datetime.now()
                        
                        # Création et stockage du message
                        chat_message = ChatMessage(timestamp=timestamp, username=user, content=msg)
                        self.messages.append(chat_message)
                        
                        # Affichage formaté
                        time_str = timestamp.strftime("%H:%M:%S.%f")[:-3]
                        print(f"[\033[95m{time_str}\033[0m] \033[94m{user}\033[0m: \033[92m{msg}\033[0m")

                except websockets.exceptions.ConnectionClosed:
                    print("\033[91m⚠️ Connexion fermée, reconnexion en cours...\033[0m")
                    break

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

# Exemple d'utilisation
if __name__ == "__main__":
    CHANNEL = "crocodyletv"
    bot = TwitchChatBot(CHANNEL)
    bot.run()