import logging
import os
import uuid
import json
import pymysql
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
)

# Config dosyasını oku
def load_config():
    try:
        with open('config.json', 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        logging.error(f"Config dosyası okunamadı: {e}")
        return {
            "bot_token": "8080399170:AAEAIZA_595xNhZuyDr4KBhaHDi62oEydOg",
            "domain": "http://papiplay.net",
            "webapp_secret": "gizli_anahtar_buraya",
            "groups": {"active_group_id": None, "allowed_groups": []},
            "database": {
                "host": "localhost",
                "user": "root",
                "password": "",
                "database": "slot_game",
                "charset": "utf8mb4"
            },
            "settings": {
                "allow_private_messages": True,
                "allow_all_groups": False,
                "initial_credits": 5000,
                "token_expiry_hours": 24
            },
            "messages": {
                "welcome": "🎮 Oyuna girmek için aşağıdaki butona tıklayın!",
                "error": "⚠️ Bir hata oluştu. Lütfen tekrar deneyin.",
                "not_allowed_group": "❌ Bu bot sadece izin verilen gruplarda çalışır.",
                "button_text": "🎮 Oyuna Gir"
            }
        }

# Config'i yükle
CONFIG = load_config()

def save_config():
    """Config dosyasını kaydet"""
    try:
        with open('config.json', 'w', encoding='utf-8') as f:
            json.dump(CONFIG, f, ensure_ascii=False, indent=4)
        return True
    except Exception as e:
        logging.error(f"Config kaydedilemedi: {e}")
        return False

def get_db_connection():
    """Veritabanı bağlantısı oluştur"""
    try:
        return pymysql.connect(**CONFIG['database'])
    except Exception as e:
        logging.error(f"Veritabanı bağlantı hatası: {e}")
        return None

def is_allowed_context(update: Update):
    """Mesajın izin verilen bir yerden gelip gelmediğini kontrol et"""
    # Özel mesaj kontrolü
    if update.effective_chat.type == 'private':
        return CONFIG['settings']['allow_private_messages']
    
    # Grup kontrolü
    if update.effective_chat.type in ['group', 'supergroup']:
        # Tüm gruplara izin verilmişse
        if CONFIG['settings']['allow_all_groups']:
            return True
        
        # Sadece belirli gruplara izin verilmişse
        chat_id = update.effective_chat.id
        return chat_id in CONFIG['groups']['allowed_groups']
    
    return False

async def papiplay(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Oyunu başlatan komut - Normal URL versiyonu"""
    # İzin kontrolü
    if not is_allowed_context(update):
        if update.effective_chat.type in ['group', 'supergroup']:
            await update.message.reply_text(CONFIG['messages']['not_allowed_group'])
        return
    
    user_id = update.effective_user.id
    username = update.effective_user.username or update.effective_user.first_name
    
    logging.info(f"Papiplay komutu: User ID: {user_id}, Username: {username}, Chat: {update.effective_chat.id}")
    
    # WebApp URL'si (Telegram onu Mini App olarak açacak)
    webapp_url = f"{CONFIG['domain']}/webapp.php"
    
    # Normal URL butonu (WebApp desteği yoksa)
    keyboard = [
        [InlineKeyboardButton(
            text=CONFIG['messages']['button_text'],
            url=webapp_url
        )]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    
    # Mesajı gönder
    await update.message.reply_text(
        CONFIG['messages']['welcome'],
        reply_markup=reply_markup
    )
    
    # Not mesajı
    await update.message.reply_text(
        "📱 Not: Eğer oyun tarayıcıda açılıyorsa, lütfen Telegram'ı güncelleyin veya mobil uygulamayı kullanın.",
        parse_mode='Markdown'
    )

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Start komutu"""
    await papiplay(update, context)

async def addgroup(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Grubu izin verilenler listesine ekle (sadece admin)"""
    if update.effective_user.id not in [8013391949]:
        return
    
    if update.effective_chat.type in ['group', 'supergroup']:
        chat_id = update.effective_chat.id
        if chat_id not in CONFIG['groups']['allowed_groups']:
            CONFIG['groups']['allowed_groups'].append(chat_id)
            save_config()
            await update.message.reply_text(f"✅ Bu grup eklendi! Grup ID: {chat_id}")
        else:
            await update.message.reply_text("ℹ️ Bu grup zaten ekli.")
    else:
        await update.message.reply_text("⚠️ Bu komut sadece gruplarda kullanılabilir.")

async def removegroup(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Grubu izin verilenler listesinden çıkar (sadece admin)"""
    if update.effective_user.id not in [8013391949]:
        return
    
    if update.effective_chat.type in ['group', 'supergroup']:
        chat_id = update.effective_chat.id
        if chat_id in CONFIG['groups']['allowed_groups']:
            CONFIG['groups']['allowed_groups'].remove(chat_id)
            save_config()
            await update.message.reply_text(f"❌ Bu grup kaldırıldı! Grup ID: {chat_id}")
        else:
            await update.message.reply_text("ℹ️ Bu grup zaten listede yok.")
    else:
        await update.message.reply_text("⚠️ Bu komut sadece gruplarda kullanılabilir.")

async def groupinfo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Grup bilgilerini göster"""
    info = f"📊 **Grup Bilgileri**\n\n"
    info += f"Chat Type: {update.effective_chat.type}\n"
    info += f"Chat ID: {update.effective_chat.id}\n"
    info += f"Chat Title: {update.effective_chat.title}\n"
    info += f"User ID: {update.effective_user.id}\n"
    info += f"Username: @{update.effective_user.username}\n\n"
    
    if update.effective_chat.type in ['group', 'supergroup']:
        is_allowed = update.effective_chat.id in CONFIG['groups']['allowed_groups']
        info += f"Bot İzni: {'✅ Var' if is_allowed else '❌ Yok'}"
    
    await update.message.reply_text(info)

def main():
    """Bot başlatma fonksiyonu"""
    application = ApplicationBuilder().token(CONFIG['bot_token']).build()
    
    # Komutları kaydet
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("papiplay", papiplay))
    application.add_handler(CommandHandler("addgroup", addgroup))
    application.add_handler(CommandHandler("removegroup", removegroup))
    application.add_handler(CommandHandler("groupinfo", groupinfo))
    
    # Botu başlat
    logging.info("Bot başlatılıyor...")
    application.run_polling()

if __name__ == '__main__':
    main() 