import sys
import logging
import random
import string
import asyncio
from urllib.parse import quote  # URL kodlaması için
import aiohttp
import mysql.connector
from mysql.connector import Error, pooling
from telegram import Update, ForceReply, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import Application, MessageHandler, filters, CallbackContext

# MySQL bağlantı bilgilerini ayarlayın
db_config = {
    'user': 'bayconti_backoffice',
    'password': '34trabzon61',
    'host': '213.136.71.24',
    'database': 'bayconti_backoffice',
    # C eklentisi yerine saf Python surucu: native cokme (ACCESS_VIOLATION) riskini kaldirir
    'use_pure': True
}

# MySQL bağlantı havuzunu oluşturun (havuz sayesinde sürekli yeni bağlantı açılmaz)
# Havuz boyutunu 20’ye çıkararak yoğun trafik altında daha fazla paralel bağlantıya izin veriyoruz.
pool = pooling.MySQLConnectionPool(pool_name="mypool", pool_size=20, **db_config)

# URL kontrolü için endpoint
verification_url = "https://baycontipro.com/deneme/"

# Windows'ta stdout cp1252 oldugu icin Turkce karakterli log satirlari
# UnicodeEncodeError veriyordu; akislari utf-8'e cekiyoruz.
for _akis in (sys.stdout, sys.stderr):
    try:
        _akis.reconfigure(encoding="utf-8", errors="replace")
    except Exception:
        pass

# --- Logging yapılandırması ---
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)
logger = logging.getLogger(__name__)

# Hata loglarını bir dosyaya yazmak için FileHandler ekleyelim
error_file_handler = logging.FileHandler("bot_errors.log", encoding="utf-8")
error_file_handler.setLevel(logging.ERROR)
error_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
error_file_handler.setFormatter(error_formatter)
logger.addHandler(error_file_handler)

# --- Global Error Handler ---
async def error_handler(update: object, context: CallbackContext) -> None:
    """
    Telegram bot uygulamasında meydana gelen yakalanmamış hataları loglar.
    """
    logger.error("Exception while handling an update:", exc_info=context.error)
    # Eğer kullanıcıya hata mesajı göstermek isterseniz, aşağıdaki satırı aktif edebilirsiniz:
    # if update and getattr(update, 'message', None):
    #     await update.message.reply_text("Bir hata oluştu, lütfen daha sonra tekrar deneyiniz.")

# --- Fonksiyonlar ---

# Kullanıcının kanal abonesi olup olmadığını kontrol eden fonksiyon
async def check_subscription(update: Update, context: CallbackContext) -> bool:
    user_id = update.effective_user.id
    channel_id = "@bayconti_casino"  # Örnek kanal kullanıcı adı

    try:
        member = await context.bot.get_chat_member(chat_id=channel_id, user_id=user_id)
        if member.status in ["member", "administrator", "creator"]:
            return True
        else:
            return False
    except Exception as e:
        logger.error(f"Error checking subscription: {e}", exc_info=True)
        return False

# Benzersiz kod oluşturma fonksiyonu
def generate_unique_code(length=8):
    characters = string.ascii_letters + string.digits
    unique_code = ''.join(random.choice(characters) for _ in range(length))
    return unique_code

# --- Veritabanı işlemleri için yardımcı fonksiyonlar ---

def check_username_in_db(username):
    """
    Veritabanında kullanıcı adının daha önce kaydedilip kaydedilmediğini kontrol eder.
    Bu fonksiyon havuzdaki bir bağlantıyı kullanır.
    """
    try:
        conn = pool.get_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT COUNT(*) FROM deneme_users WHERE username = %s", (username,))
        result = cursor.fetchone()
        cursor.close()
        conn.close()
        return result[0] > 0
    except Error as e:
        logger.error(f"DB Error in check_username_in_db: {e}", exc_info=True)
        raise

def insert_username_to_db(user_id, username, unique_code):
    """
    Kullanıcı bilgilerini veritabanına ekler.
    """
    try:
        conn = pool.get_connection()
        cursor = conn.cursor()
        cursor.execute(
            "INSERT INTO deneme_users (user_id, username, unique_code) VALUES (%s, %s, %s)",
            (user_id, username, unique_code)
        )
        conn.commit()
        cursor.close()
        conn.close()
    except Error as e:
        logger.error(f"Error inserting into DB: {e}", exc_info=True)
        raise

# --- Asenkron doğrulama ve kayıt işlemleri ---

async def is_valid_username(username):
    """
    Veritabanında daha önce kaydedilmiş mi kontrol eder ve 
    ardından kullanıcı adı için doğrulama URL'sine asenkron istek atar.
    
    (Kullanıcı adı email formatında olsa dahi tüm sorgulamalar yapılır.)
    """
    try:
        # Veritabanı kontrolünü ayrı iş parçacığında çalıştır
        exists = await asyncio.to_thread(check_username_in_db, username)
        if exists:
            return (
                False,
                "Deneme bonusundan daha önceden yararlandığınız için Bonus hakkınız bulunmamaktadır. "
                "Yatırım bonuslarımızdan yararlanabilirsiniz."
            )

        # Eğer kullanıcı adı email formatındaysa (içinde "@" varsa) encode işlemi atlanır.
        if "@" in username:
            url = f"{verification_url}{username}"
        else:
            url = f"{verification_url}{quote(username)}"
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                text = await response.text()
                if response.status == 200 and text == "1":
                    return True, ""
                else:
                    return False, text
    except Error as e:
        logger.error(f"Error connecting to MySQL: {e}", exc_info=True)
        return False, f"Bir hata oluştu: {e}"
    except aiohttp.ClientError as e:
        logger.error(f"HTTP Request error: {e}", exc_info=True)
        return False, "Doğrulama servisine bağlanırken bir hata oluştu."
    except Exception as e:
        logger.error(f"Unexpected error in is_valid_username: {e}", exc_info=True)
        return False, f"Bir hata oluştu: {e}"

# BONUS URL'sine istek gönderme fonksiyonu (3 denemeye kadar)
async def call_bonus_url(link: str):
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(link) as resp:
                response_text = await resp.text()
                if resp.status == 200:
                    logger.info("Bonus URL çağrısı başarılı.")
                    return
                logger.error(f"Bonus URL çağrısı başarısız. Durum kodu: {resp.status}. Yanıt: {response_text}")
    except Exception as e:
        logger.error(f"Bonus URL çağrısında hata: {e}", exc_info=True)

async def save_username(update: Update, context: CallbackContext) -> None:
    """
    Kullanıcıdan alınan kullanıcı adını doğrular ve veritabanına kaydeder.
    Ardından ilgili bonus tanımlama URL'ine asenkron istek gönderir.
    """
    # Tüm mesaj metnini al
    full_text = update.message.text if update.message else None
    if not full_text:
        # Fotograf, sticker, ses vb. metin icermeyen mesajlar: sessizce yoksay
        return
    
    # Çok satırlı (alıntılanmış) mesajlarda en sondaki satır genelde kullanıcı adıdır
    last_line = full_text.strip().split('\n')[-1].strip()
    
    # Eğer kullanıcı adı alıntılanmış (tek ya da çift tırnak) gönderilmişse, tırnakları kaldır
    if len(last_line) > 1 and (
        (last_line[0] == '"' and last_line[-1] == '"') or 
        (last_line[0] == "'" and last_line[-1] == "'")
    ):
        last_line = last_line[1:-1].strip()
    
    username = last_line  # Daha anlaşılır bir isim verelim

    user = update.effective_user

    # Kullanıcı adının geçerliliğini asenkron olarak kontrol et
    valid, message = await is_valid_username(username)
    if not valid:
        await update.message.reply_text(message)
        context.user_data['awaiting_username'] = False
        return

    # Benzersiz kod oluştur
    unique_code = generate_unique_code()

    try:
        # Veritabanına kayıt işlemini ayrı iş parçacığında çalıştır
        await asyncio.to_thread(insert_username_to_db, user.id, username, unique_code)

        # URL kodlaması: Eğer kullanıcı adı email formatındaysa encode yapılmaz.
        if "@" in username:
            encoded_username = username
        else:
            encoded_username = quote(username)
        encoded_unique_code = quote(unique_code)

        # Bonusun tanımlandığını bildiren mesajı gönder
        await update.message.reply_text(
            f'✅ Tebrikler {username}, kullanıcı adınıza deneme bonusu tanımlandı!\n'
            f'BayConti bol şanslar diler.'
        )

        # BONUS: Arka planda bonus tanımlama URL'ine asenkron istek gönderiliyor.
        link = f"https://baycontipro.com/?username={encoded_username}&uni_code={encoded_unique_code}"
        asyncio.create_task(call_bonus_url(link))

        context.user_data['awaiting_username'] = False
    except Error as e:
        logger.error(f"Error inserting into DB: {e}", exc_info=True)
        await update.message.reply_text(f"Bir hata oluştu: {e}")
        context.user_data['awaiting_username'] = False

# Mesaj geldiğinde kanal aboneliğini kontrol eden ve kullanıcı adını isteyen fonksiyon
async def handle_message(update: Update, context: CallbackContext) -> None:
    # filters.ALL her guncellemeyi yakaliyor: kanal gonderisi, servis mesaji vb.
    # Bunlarda update.message / context.user_data None olur ve handler patlardi.
    if update.message is None or context.user_data is None:
        return
    user = update.effective_user
    if 'awaiting_username' not in context.user_data or not context.user_data['awaiting_username']:
        if await check_subscription(update, context):
            await update.message.reply_text(
                'Merhaba! Kullanıcı adınızı yazın:',
                reply_markup=ForceReply(selective=True)
            )
            context.user_data['awaiting_username'] = True
        else:
            # Kanal abone olma butonu
            reply_markup = InlineKeyboardMarkup([
                [InlineKeyboardButton("Kanala Abone Olmak İçin Tıklayınız", url="https://t.me/bayconti_casino")]
            ])
            await update.message.reply_text('Lütfen önce kanala abone olun!', reply_markup=reply_markup)
    else:
        # Kullanıcı adını işleme alırken beklememesi için save_username fonksiyonunu arka planda çalıştırıyoruz.
        asyncio.create_task(save_username(update, context))

def main() -> None:
    # Telegram bot uygulamasını oluşturun
    application = Application.builder().token("8069371331:AAEUhMYiLB_ER8u9m1OYSLPyQ2u2hq5CV44").build()

    # Mesaj işlemcisini ekleyin
    application.add_handler(MessageHandler(filters.ALL, handle_message))
    
    # Global error handler ekleyelim
    application.add_error_handler(error_handler)

    # Botu başlatın
    application.run_polling()

if __name__ == '__main__':
    main()
