import asyncio
import os
import time
from telethon import TelegramClient
from telethon.tl.types import MessageMediaPhoto, MessageMediaDocument
from telethon.errors import FloodWaitError
from tqdm import tqdm
from colorama import Fore, Style

api_id = 20162818
api_hash = '0689ef0945647548c4176ecd39fe5fdd'
session_name = 'session'

os.makedirs('downloads/photos', exist_ok=True)
os.makedirs('downloads/videos', exist_ok=True)
os.makedirs('downloads/documents', exist_ok=True)

async def send_media():
    source_channel = input("Enter source channel username (with @): ")
    destination_channel = input("Enter destination channel username (with @): ")

    print("\nChoose media type to send:")
    print("1. Photos only")
    print("2. Videos only")
    print("3. Documents only")
    print("4. All media")
    choice = input("Enter your choice (1/2/3/4): ")

    async with TelegramClient(session_name, api_id, api_hash) as client:
        print(Fore.CYAN + "\n📦 Fetching media messages..." + Style.RESET_ALL)
        messages = []
        async for msg in client.iter_messages(source_channel):
            if msg.media:
                if choice == '1' and isinstance(msg.media, MessageMediaPhoto):
                    messages.append(msg)
                elif choice == '2' and isinstance(msg.media, MessageMediaDocument) and msg.file and msg.file.mime_type.startswith('video'):
                    messages.append(msg)
                elif choice == '3' and isinstance(msg.media, MessageMediaDocument) and not msg.file.mime_type.startswith('video'):
                    messages.append(msg)
                elif choice == '4':
                    messages.append(msg)

        print(Fore.GREEN + f"✅ Found {len(messages)} matching media.\n" + Style.RESET_ALL)

        confirm = input("Proceed with sending? (y/n): ")
        if confirm.lower() != 'y':
            print("❌ Cancelled.")
            return

        delay = 2
        with tqdm(total=len(messages), bar_format="{l_bar}%s{bar}%s{r_bar}" % (Fore.RED, Style.RESET_ALL)) as pbar:
            for msg in messages:
                try:
                    await client.send_file(destination_channel, file=msg.media)
                    await asyncio.sleep(delay)
                    delay += 1
                except FloodWaitError as e:
                    print(f"⏳ Flood wait: sleeping for {e.seconds} seconds...")
                    await asyncio.sleep(e.seconds)
                    delay = 2
                except Exception as e:
                    print(f"❌ Failed to send message: {e}")
                pbar.update(1)

        print(Fore.GREEN + "\n✅ Done sending media!" + Style.RESET_ALL)

def main():
    asyncio.run(send_media())
