import logging
import os
import uuid
import json
import pymysql
import hashlib
import time
from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, filters

# Loglama ayarları
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.DEBUG
)

# 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",  # Güvenlik için
            "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",
                "group_game_text": "🎮 Oyuna girmek için aşağıdaki butona tıklayın!"
            }
        }

# 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']:
            logging.info("Tüm gruplara izin var")
            return True
        
        # Sadece belirli gruplara izin verilmişse
        chat_id = update.effective_chat.id
        
        logging.info(f"Grup ID: {chat_id}")
        logging.info(f"İzinli gruplar: {CONFIG['groups']['allowed_groups']}")
        
        is_allowed = chat_id in CONFIG['groups']['allowed_groups']
        logging.info(f"İzin durumu: {is_allowed}")
        
        return is_allowed
    
    return False

def create_webapp_hash(user_id):
    """Güvenli webapp hash oluştur"""
    timestamp = int(time.time())
    data = f"{user_id}:{timestamp}:{CONFIG.get('webapp_secret', 'default_secret')}"
    hash_value = hashlib.sha256(data.encode()).hexdigest()[:16]
    return f"{timestamp}:{hash_value}"

async def papiplay(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Oyunu başlatan komut"""
    try:
        logging.info(f"Papiplay komutu alındı: Chat ID: {update.effective_chat.id}, Chat Type: {update.effective_chat.type}")
        
        # İzin kontrolü
        if not is_allowed_context(update):
            if update.effective_chat.type in ['group', 'supergroup']:
                logging.warning(f"Grup izinli değil: {update.effective_chat.id}")
                await update.message.reply_text(CONFIG['messages']['not_allowed_group'])
            else:
                logging.warning(f"İzin verilmeyen context: {update.effective_chat.type}")
            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}")
        
        # Grup veya özel sohbet kontrolü
        if update.effective_chat.type in ['group', 'supergroup']:
            # Bot bilgilerini al
            bot_info = await context.bot.get_me()
            bot_username = bot_info.username
            
            # Botun özel sohbetine yönlendiren "start_game" parametreli bir URL oluştur
            start_game_url = f"https://t.me/{bot_username}?start=start_game_{user_id}"
            
            keyboard = [
                [InlineKeyboardButton(
                    text="🎮 BAŞLAT",
                    url=start_game_url
                )]
            ]
            
            message = CONFIG['messages'].get('group_game_text', '🎮 BAŞLAT')
            logging.info(f"Grup mesajı hazırlandı: {message}")
        else:
            # Özel sohbet için WebApp butonu
            webapp_url = f"{CONFIG['domain']}/webapp.php"
            keyboard = [
                [InlineKeyboardButton(
                    text=CONFIG['messages']['button_text'],
                    web_app=WebAppInfo(url=webapp_url)
                )]
            ]
            message = CONFIG['messages']['welcome']
            logging.info(f"Özel sohbet mesajı hazırlandı: {message}")
            
        reply_markup = InlineKeyboardMarkup(keyboard)
        
        # Yerel fotoğraf ile mesaj gönder
        try:
            # Yerel fotoğraf dosyasının yolunu belirle
            photo_path = os.path.join(os.path.dirname(__file__), "thumbnail_bot", "telegram_foto2.png")
            logging.info(f"Fotoğraf yolu: {photo_path}")
            
            # Dosya var mı kontrol et
            if os.path.exists(photo_path):
                # Fotoğraf dosyasını aç ve gönder
                with open(photo_path, 'rb') as photo_file:
                    await update.message.reply_photo(
                        photo=photo_file,
                        caption=message,
                        reply_markup=reply_markup
                    )
                logging.info("Yerel fotoğraf ile mesaj gönderildi")
                return
            else:
                logging.warning(f"Fotoğraf dosyası bulunamadı: {photo_path}")
                
        except Exception as photo_error:
            logging.warning(f"Yerel fotoğraf gönderilemedi: {photo_error}")
        
        # Fotoğraf başarısız olduysa normal metin mesajı gönder
        await update.message.reply_text(
            message,
            reply_markup=reply_markup
        )
        logging.info("Metin mesajı gönderildi")
        
    except Exception as e:
        logging.exception(f"PAPIPLAY HATASI: {e}")
        try:
            await update.message.reply_text(CONFIG['messages']['error'])
        except Exception as reply_error:
            logging.error(f"Hata mesajı gönderilemedi: {reply_error}")

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Start komutu"""
    try:
        # Parametreler varsa kontrol et
        referral_telegram_id = None
        if context.args and len(context.args) > 0:
            command = context.args[0]
            
            # "start_game" parametresi gelirse doğrudan WebApp aç
            if command.startswith("start_game_"):
                # Özel sohbette olduğumuzdan emin olalım
                if update.effective_chat.type == 'private':
                    # Direkt WebApp'i aç
                    webapp_url = f"{CONFIG['domain']}/webapp.php"
                    keyboard = [
                        [InlineKeyboardButton(
                            text="🎮 HEMEN OYNA",
                            web_app=WebAppInfo(url=webapp_url)
                        )]
                    ]
                    reply_markup = InlineKeyboardMarkup(keyboard)
                    
                    # Hızlı mesaj gönder
                    await update.message.reply_text(
                        text="🎮 Oyun hazır! Hemen başlamak için tıklayın:",
                        reply_markup=reply_markup
                    )
                    
                return
            
            # Referral link kontrolü - r_TELEGRAM_ID formatı
            elif command.startswith("r_"):
                referral_telegram_id = command[2:]  # r_ kısmını kaldır
                if referral_telegram_id and referral_telegram_id.isdigit():
                    # WebApp URL'sine referral parametresi ekle
                    webapp_url = f"{CONFIG['domain']}/webapp.php?ref={referral_telegram_id}"
                else:
                    webapp_url = f"{CONFIG['domain']}/webapp.php"
            else:
                webapp_url = f"{CONFIG['domain']}/webapp.php"
        else:
            webapp_url = f"{CONFIG['domain']}/webapp.php"
        
        # Normal start mesajı gönder
        keyboard = [
            [InlineKeyboardButton(
                text=CONFIG['messages']['button_text'],
                web_app=WebAppInfo(url=webapp_url)
            )]
        ]
        reply_markup = InlineKeyboardMarkup(keyboard)
        
        # Fotoğraf ile göndermeyi dene
        photo_path = 'thumbnail_bot/telegram_foto.png'
        if os.path.exists(photo_path):
            await update.message.reply_photo(
                photo=open(photo_path, 'rb'),
                caption=CONFIG['messages']['welcome'],
                reply_markup=reply_markup
            )
        else:
            await update.message.reply_text(
                text=CONFIG['messages']['welcome'],
                reply_markup=reply_markup
            )
            
    except Exception as e:
        logging.error(f"Start komutu hatası: {e}")
        await update.message.reply_text(CONFIG['messages']['error'])

async def addgroup(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Grubu izin verilenler listesine ekle (sadece admin)"""
    if update.effective_user.id not in [8013391949, 1761901617]:
        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, 1761901617]:
        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)

    
async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Hataları yakala ve logla"""
    logging.error(f"Hata oluştu: {context.error}")
    logging.exception(context.error)

def main():
    """Bot başlatma fonksiyonu"""
    application = ApplicationBuilder().token(CONFIG['bot_token']).build()
    
    # Komutları özel sırayla kaydet
    application.add_handler(CommandHandler("papiplay", papiplay))  # İlk sıraya koyduk
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("groupinfo", groupinfo))
    application.add_handler(CommandHandler("addgroup", addgroup))
    application.add_handler(CommandHandler("removegroup", removegroup))
    
    # ! ile başlayan mesajlar için handler ekle
    async def handle_exclamation_commands(update: Update, context: ContextTypes.DEFAULT_TYPE):
        """! ile başlayan komutları işle"""
        if update.message and update.message.text:
            text = update.message.text.lower().strip()
            if text == "!papiplay":
                await papiplay(update, context)
    
    # Metin mesajları için handler ekle (! komutları için)
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_exclamation_commands))
    
    # Hata işleyici ekle
    application.add_error_handler(error_handler)
    
    # Botu başlat
    logging.info("Bot başlatılıyor...")
    application.run_polling()

  

if __name__ == '__main__':
    main() 