import os
import logging
import sys
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, ContextTypes, filters
from downloader import VideoDownloader

# Enable logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)
logger = logging.getLogger(__name__)

# Initialize downloader
downloader = VideoDownloader(download_path='downloads')

# Bot token
TOKEN = "7832199348:AAFZqmUwLbMoC_8zVCNQ5otAhsanABwvNbo"

# Define command handlers
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Send a message when the command /start is issued."""
    user = update.effective_user
    await update.message.reply_text(
        f"Halo {user.first_name}! 👋\n\n"
        f"Saya adalah bot pengunduh video dari berbagai platform.\n\n"
        f"Kirimkan link video dari YouTube, Facebook, Instagram, TikTok, atau platform lainnya, "
        f"dan saya akan mengunduhkannya untuk Anda.\n\n"
        f"Gunakan /help untuk melihat bantuan lebih lanjut."
    )

async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Send a message when the command /help is issued."""
    await update.message.reply_text(
        "🔍 *Cara Menggunakan Bot Pengunduh Video* 🔍\n\n"
        "1️⃣ Kirim link video dari platform yang didukung:\n"
        "   • YouTube\n"
        "   • Facebook\n"
        "   • Instagram\n"
        "   • TikTok\n"
        "   • Dan platform lainnya\n\n"
        "2️⃣ Pilih format unduhan (video atau audio)\n\n"
        "3️⃣ Tunggu hingga proses unduhan selesai\n\n"
        "4️⃣ Bot akan mengirimkan file video/audio yang telah diunduh\n\n"
        "*Perintah yang tersedia:*\n"
        "/start - Memulai bot\n"
        "/help - Menampilkan bantuan\n"
        "/about - Informasi tentang bot\n\n"
        "⚠️ *Catatan:* Ukuran file maksimum yang dapat dikirim melalui Telegram adalah 50MB",
        parse_mode='Markdown'
    )

async def about_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Send a message when the command /about is issued."""
    await update.message.reply_text(
        "🤖 *Bot Pengunduh Video* 🤖\n\n"
        "Bot ini memungkinkan Anda mengunduh video dari berbagai platform seperti "
        "YouTube, Facebook, Instagram, TikTok, dan lainnya.\n\n"
        "Dibuat dengan ❤️ menggunakan:\n"
        "• Python\n"
        "• python-telegram-bot\n"
        "• yt-dlp\n"
        "• pytube\n\n"
        "Versi: 1.0.0",
        parse_mode='Markdown'
    )

async def handle_url(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Handle URLs sent by the user."""
    url = update.message.text.strip()
    
    # Check if the message contains a valid URL
    if not (url.startswith('http://') or url.startswith('https://')):
        await update.message.reply_text("Mohon kirimkan URL yang valid.")
        return
    
    # Store URL in user data
    context.user_data['url'] = url
    
    # Determine platform
    platform = downloader.get_platform(url)
    platform_name = platform.capitalize()
    
    # Send options to user
    keyboard = [
        [
            InlineKeyboardButton("Video 🎬", callback_data=f"video_{platform}"),
            InlineKeyboardButton("Audio 🎵", callback_data=f"audio_{platform}")
        ]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    
    await update.message.reply_text(
        f"Link {platform_name} terdeteksi! Pilih format yang ingin diunduh:",
        reply_markup=reply_markup
    )

async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Handle button callbacks."""
    query = update.callback_query
    await query.answer()
    
    # Get callback data
    data = query.data
    url = context.user_data.get('url')
    
    if not url:
        await query.edit_message_text("Sesi telah kedaluwarsa. Silakan kirim URL lagi.")
        return
    
    # Parse callback data
    format_type, platform = data.split('_')
    audio_only = format_type == 'audio'
    
    # Send processing message
    await query.edit_message_text(f"⏳ Sedang memproses {'audio' if audio_only else 'video'} dari {platform.capitalize()}...\nMohon tunggu sebentar.")
    
    try:
        # Download the video/audio
        result = downloader.download(url, audio_only=audio_only)
        
        if not result['success']:
            await context.bot.send_message(
                chat_id=update.effective_chat.id,
                text=f"❌ Gagal mengunduh: {result['error']}"
            )
            return
        
        file_path = result['file_path']
        title = result['title']
        format_name = 'MP3' if audio_only else 'Video'
        
        # Check file size
        file_size = os.path.getsize(file_path) / (1024 * 1024)  # Size in MB
        
        if file_size > 50:
            await context.bot.send_message(
                chat_id=update.effective_chat.id,
                text=f"⚠️ File terlalu besar ({file_size:.1f}MB) untuk dikirim melalui Telegram (batas 50MB)."
            )
            # Delete the file to save space
            os.remove(file_path)
            return
        
        # Send status message
        await context.bot.send_message(
            chat_id=update.effective_chat.id,
            text=f"✅ {format_name} berhasil diunduh!\nJudul: {title}\nUkuran: {file_size:.1f}MB\n\nMengirim file..."
        )
        
        # Send the file
        if audio_only:
            await context.bot.send_audio(
                chat_id=update.effective_chat.id,
                audio=open(file_path, 'rb'),
                title=title,
                caption=f"🎵 {title}"
            )
        else:
            await context.bot.send_video(
                chat_id=update.effective_chat.id,
                video=open(file_path, 'rb'),
                caption=f"🎬 {title}"
            )
        
        # Delete the file to save space
        os.remove(file_path)
        
    except Exception as e:
        logger.error(f"Error in button_callback: {e}")
        await context.bot.send_message(
            chat_id=update.effective_chat.id,
            text=f"❌ Terjadi kesalahan: {str(e)}"
        )

def main() -> None:
    """Start the bot."""
    # Create the Application
    application = Application.builder().token(TOKEN).build()

    # Add handlers
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("help", help_command))
    application.add_handler(CommandHandler("about", about_command))
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_url))
    application.add_handler(CallbackQueryHandler(button_callback))

    # Create downloads directory if it doesn't exist
    os.makedirs('downloads', exist_ok=True)

    # Log startup message
    logger.info("Bot started. Press Ctrl+C to stop.")
    
    try:
        # Run the bot until the user presses Ctrl-C
        application.run_polling(allowed_updates=Update.ALL_TYPES)
    except KeyboardInterrupt:
        logger.info("Bot stopped by user.")
    except Exception as e:
        logger.error(f"Error running bot: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()
