#!/usr/bin/env python3
"""
Test - collect voice messages from a chat and download them.
"""

import asyncio
from pathlib import Path
from whatsplay import Client
from whatsplay.auth import LocalProfileAuth
from whatsplay.object.message import VoiceMessage


SESSION_DIR = "/home/markbusking/proyectos/tools/TransWhatsapp/wsp_session"
CHAT_NAME = "Nahuel"
DOWNLOADS_DIR = Path("./voice_downloads")


async def main():
    print("Creating client...")
    auth = LocalProfileAuth(SESSION_DIR)
    client = Client(auth=auth, headless=True)

    @client.event("on_logged_in")
    async def on_ready():
        print("  -> on_logged_in event fired!")

        try:
            print(f"Opening chat '{CHAT_NAME}'...")
            await client.open(CHAT_NAME)

            # Wait for messages to load
            await asyncio.sleep(3)

            print("Collecting messages...")
            messages = await client.collect_messages()
            print(f"Total messages collected: {len(messages)}")

            voice_messages = [msg for msg in messages if isinstance(msg, VoiceMessage)]
            print(f"Found {len(voice_messages)} voice messages")

            # Download all voice messages
            downloaded = await client.download_all_files(str(DOWNLOADS_DIR))
            print(f"Downloaded {len(downloaded)} files\n")

            for i, info in enumerate(downloaded):
                print(f"  [{i}] {info['path'].name}")

        except Exception as e:
            import traceback

            print(f"Error: {e}")
            traceback.print_exc()
        finally:
            await client.stop()
            print("\nDone!")

    print("Starting client...")
    await client.start()


if __name__ == "__main__":
    asyncio.run(main())
