import logging
import os
import json
import traceback
from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, filters

# Loglama ayarları
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)

# Bot token
BOT_TOKEN = "8080399170:AAEAIZA_595xNhZuyDr4KBhaHDi62oEydOg"

async def debug(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Debug komutu - tüm bilgileri göster"""
    try:
        # Mesaj bilgileri
        debug_info = "📊 **Debug Bilgileri**\n\n"
        debug_info += f"Chat Type: {update.effective_chat.type}\n"
        debug_info += f"Chat ID: {update.effective_chat.id}\n"
        debug_info += f"Message ID: {update.message.message_id}\n"
        debug_info += f"User ID: {update.effective_user.id}\n"
        debug_info += f"Username: @{update.effective_user.username}\n"
        debug_info += f"First Name: {update.effective_user.first_name}\n"
        
        # Komut ve argümanlar
        if update.message.text.startswith('/'):
            parts = update.message.text.split(' ', 1)
            command = parts[0]
            args = parts[1] if len(parts) > 1 else ''
            debug_info += f"\nCommand: {command}\n"
            debug_info += f"Args: {args}\n"
        
        # Normal buton testi
        keyboard = [
            [InlineKeyboardButton("Normal Buton", url="https://papiplay.net")]
        ]
        reply_markup = InlineKeyboardMarkup(keyboard)
        
        await update.message.reply_text(debug_info, reply_markup=reply_markup)
        
    except Exception as e:
        error_msg = f"❌ Hata: {str(e)}\n\n"
        error_msg += traceback.format_exc()
        await update.message.reply_text(error_msg)

async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Hatalar için genel handler"""
    logging.error("Exception while handling an update:", exc_info=context.error)
    
    # Hata mesajı oluştur
    tb_list = traceback.format_exception(None, context.error, context.error.__traceback__)
    tb_string = ''.join(tb_list)
    
    # Hata mesajını kısalt
    error_message = f"❌ Bir hata oluştu: {context.error}\n\n"
    
    # Hata bilgisini terminal loglarına yaz
    logging.error(f"Hata: {tb_string}")
    
    # Hata mesajını kullanıcıya gönder (varsa)
    if update and hasattr(update, 'effective_chat'):
        await context.bot.send_message(
            chat_id=update.effective_chat.id, 
            text=error_message
        )

def main():
    """Bot başlatma fonksiyonu"""
    application = ApplicationBuilder().token(BOT_TOKEN).build()
    
    # Hata handler'ı ekle
    application.add_error_handler(error_handler)
    
    # Komutları kaydet
    application.add_handler(CommandHandler("debug", debug))
    
    # Botu başlat
    logging.info("Debug bot başlatılıyor...")
    application.run_polling()

if __name__ == '__main__':
    main() 