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ı - DAHA DETAYLI
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.DEBUG  # DEBUG seviyesine çıkardık
)

# Config dosyasını oku
def load_config():
    try:
        with open('config.json', 'r', encoding='utf-8') as f:
            config = json.load(f)
            logging.info(f"Config yüklendi: {json.dumps(config, indent=2)}")
            return config
    except Exception as e:
        logging.error(f"Config dosyası okunamadı: {e}")
        # Varsayılan config
        return {
            "bot_token": "8080399170:AAEAIZA_595xNhZuyDr4KBhaHDi62oEydOg",
            "domain": "http://papiplay.net",
            "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": "Merhaba {username}! 🎰\n\nOyun merkezine gitmek için aşağıdaki butona tıklayın.\nKredileriniz ve oyun ilerlemeniz otomatik olarak kaydedilecek.",
                "error": "⚠️ Bir hata oluştu. Lütfen tekrar deneyin.",
                "not_allowed_group": "❌ Bu bot sadece izin verilen gruplarda çalışır.",
                "button_text": "🎮 Oyun Merkezine Git"
            }
        }

# 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 test_db_connection():
    """Veritabanı bağlantısını test et"""
    try:
        conn = pymysql.connect(**CONFIG['database'])
        logging.info("✅ Veritabanı bağlantısı BAŞARILI!")
        
        # Tabloları kontrol et
        with conn.cursor() as cursor:
            cursor.execute("SHOW TABLES")
            tables = cursor.fetchall()
            logging.info(f"Veritabanındaki tablolar: {tables}")
            
            # Users tablosunu kontrol et
            cursor.execute("SELECT COUNT(*) FROM users")
            user_count = cursor.fetchone()[0]
            logging.info(f"Toplam kullanıcı sayısı: {user_count}")
            
        conn.close()
        return True
    except Exception as e:
        logging.error(f"❌ Veritabanı bağlantı HATASI: {e}")
        return False

def get_db_connection():
    """Veritabanı bağlantısı oluştur"""
    try:
        logging.debug(f"Veritabanına bağlanılıyor: {CONFIG['database']['host']}")
        conn = pymysql.connect(**CONFIG['database'])
        logging.debug("Veritabanı bağlantısı başarılı")
        return conn
    except Exception as e:
        logging.error(f"Veritabanı bağlantı hatası: {e}")
        logging.error(f"Host: {CONFIG['database']['host']}")
        logging.error(f"Database: {CONFIG['database']['database']}")
        return None

def is_allowed_context(update: Update):
    """Mesajın izin verilen bir yerden gelip gelmediğini kontrol et"""
    chat_type = update.effective_chat.type
    chat_id = update.effective_chat.id
    
    logging.debug(f"Chat Type: {chat_type}, Chat ID: {chat_id}")
    
    # Özel mesaj kontrolü
    if chat_type == 'private':
        allowed = CONFIG['settings']['allow_private_messages']
        logging.debug(f"Özel mesaj izni: {allowed}")
        return allowed
    
    # Grup kontrolü
    if chat_type in ['group', 'supergroup']:
        # Tüm gruplara izin verilmişse
        if CONFIG['settings']['allow_all_groups']:
            logging.debug("Tüm gruplara izin var")
            return True
        
        # Sadece belirli gruplara izin verilmişse
        allowed = chat_id in CONFIG['groups']['allowed_groups']
        logging.debug(f"Grup {chat_id} izinli mi: {allowed}")
        logging.debug(f"İzinli gruplar: {CONFIG['groups']['allowed_groups']}")
        return allowed
    
    return False

def register_user_and_create_token(telegram_id, username):
    """Kullanıcıyı kaydet veya güncelle ve token oluştur"""
    logging.info(f"Token oluşturma başladı - Telegram ID: {telegram_id}, Username: {username}")
    
    conn = get_db_connection()
    if not conn:
        logging.error("Veritabanı bağlantısı kurulamadı!")
        return None
    
    try:
        with conn.cursor() as cursor:
            # Kullanıcıyı ekle veya güncelle
            sql = """
                INSERT INTO users (telegram_id, username)
                VALUES (%s, %s)
                ON DUPLICATE KEY UPDATE 
                    username = VALUES(username),
                    last_login = CURRENT_TIMESTAMP
            """
            cursor.execute(sql, (telegram_id, username))
            logging.debug(f"Kullanıcı eklendi/güncellendi. Affected rows: {cursor.rowcount}")
            
            # Kullanıcı ID'sini al
            if cursor.lastrowid:
                user_id = cursor.lastrowid
                logging.debug(f"Yeni kullanıcı ID: {user_id}")
                # Yeni kullanıcı için kredi ekle
                sql = "INSERT INTO user_stats (user_id, credits) VALUES (%s, %s)"
                cursor.execute(sql, (user_id, CONFIG['settings']['initial_credits']))
                logging.debug("Başlangıç kredisi eklendi")
            else:
                # Mevcut kullanıcının ID'sini al
                sql = "SELECT id FROM users WHERE telegram_id = %s"
                cursor.execute(sql, (telegram_id,))
                result = cursor.fetchone()
                user_id = result[0]
                logging.debug(f"Mevcut kullanıcı ID: {user_id}")
            
            # Benzersiz token oluştur
            token = str(uuid.uuid4())
            logging.debug(f"Token oluşturuldu: {token}")
            
            # Eski tokenları sil
            sql = "DELETE FROM tokens WHERE user_id = %s"
            cursor.execute(sql, (user_id,))
            logging.debug(f"Eski tokenlar silindi. Affected rows: {cursor.rowcount}")
            
            # Yeni token ekle
            sql = """
                INSERT INTO tokens (user_id, token, expires_at)
                VALUES (%s, %s, DATE_ADD(NOW(), INTERVAL %s HOUR))
            """
            cursor.execute(sql, (user_id, token, CONFIG['settings']['token_expiry_hours']))
            logging.debug(f"Yeni token eklendi. Affected rows: {cursor.rowcount}")
            
            conn.commit()
            logging.info(f"✅ Token başarıyla oluşturuldu: {token} - User: {username}")
            return token
            
    except Exception as e:
        logging.error(f"❌ Kullanıcı kayıt hatası: {e}")
        logging.exception("Detaylı hata:")
        conn.rollback()
        return None
    finally:
        conn.close()

async def papiplay(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Oyunu başlatan komut"""
    logging.info("=== PAPIPLAY KOMUTU BAŞLADI ===")
    
    # İ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'])
            logging.warning("Grup izinli değil!")
        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}")
    
    # Token oluştur ve veritabanına kaydet
    token = register_user_and_create_token(user_id, username)
    
    if not token:
        await update.message.reply_text(CONFIG['messages']['error'])
        logging.error("Token oluşturulamadı!")
        return
    
    # Oyun URL'si oluştur
    game_url = f"{CONFIG['domain']}/index.php?token={token}"
    logging.info(f"Oyun URL: {game_url}")
    
    # Inline buton oluştur
    keyboard = [
        [InlineKeyboardButton(CONFIG['messages']['button_text'], url=game_url)]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    
    await update.message.reply_text(
        CONFIG['messages']['welcome'].format(username=username),
        reply_markup=reply_markup
    )
    logging.info("=== PAPIPLAY KOMUTU TAMAMLANDI ===")

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Start komutu"""
    await papiplay(update, context)

async def test_db(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Veritabanı bağlantısını test et"""
    if update.effective_user.id not in [8013391949]:
        return
    
    if test_db_connection():
        await update.message.reply_text("✅ Veritabanı bağlantısı başarılı!")
    else:
        await update.message.reply_text("❌ Veritabanı bağlantısı başarısız! Log'ları kontrol edin.")

async def addgroup(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Grubu izin verilenler listesine ekle (sadece admin)"""
    # Sadece bot adminleri kullanabilir
    if update.effective_user.id not in [8013391949, 1761901617]:  # Buraya kendi Telegram ID'nizi ekleyin
        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)"""
    # Sadece bot adminleri kullanabilir
    if update.effective_user.id not in [8013391949, 1761901617]:  # Buraya kendi Telegram ID'nizi ekleyin
        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"""
    logging.info("Bot başlatılıyor...")
    logging.info(f"Bot Token: {CONFIG['bot_token'][:10]}...")
    logging.info(f"Domain: {CONFIG['domain']}")
    logging.info(f"Database Host: {CONFIG['database']['host']}")
    
    # Veritabanı bağlantısını test et
    test_db_connection()
    
    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))
    application.add_handler(CommandHandler("testdb", test_db))
    
    # Botu başlat
    logging.info("Bot polling başlatılıyor...")
    application.run_polling()

if __name__ == '__main__':
    main() 