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': 'istinyecasinoort_backoffice',
    'password': '34trabzon61',
    'host': '213.136.71.24',
    'database': 'istinyecasinoort_backoffice'
}

# MySQL bağlantı havuzunu oluşturun
pool = pooling.MySQLConnectionPool(pool_name="mypool", pool_size=20, **db_config)

# URL kontrolü için endpoint
verification_url = "https://bonus.istinyecasinoortaklik.com/deneme/"

# --- Logging yapılandırması ---
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)
logger = logging.getLogger(__name__)
error_file_handler = logging.FileHandler("bot_errors.log")
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)

# --- Kullanıcı-bazlı kilitler (aynı anda birden fazla iş tetiklenmesin) ---
processing_locks = {}  # user_id -> asyncio.Lock

def get_user_lock(user_id: int) -> asyncio.Lock:
    lock = processing_locks.get(user_id)
    if lock is None:
        lock = asyncio.Lock()
        processing_locks[user_id] = lock
    return lock

# --- Global Error Handler ---
async def error_handler(update: object, context: CallbackContext) -> None:
    logger.error("Exception while handling an update:", exc_info=context.error)

# --- 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 = "@istinyecasinoresmi"
    try:
        member = await context.bot.get_chat_member(chat_id=channel_id, user_id=user_id)
        return member.status in ["member", "administrator", "creator"]
    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 ---

def check_username_in_db(username):
    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):
    """
    Duplicate (UNIQUE) hatasını yakalar ve tekrar raise ederiz ki üst katman uygun mesaj versin.
    """
    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 mysql.connector.IntegrityError as e:
        # 1062: Duplicate entry
        if e.errno == 1062:
            raise e
        logger.error(f"IntegrityError inserting into DB: {e}", exc_info=True)
        raise
    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):
    """
    DB'de var mı kontrol + doğrulama servisi.
    """
    try:
        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."
            )

        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):
    max_attempts = 3
    for attempt in range(max_attempts):
        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(f"Bonus URL çağrısı {attempt+1}. denemede başarılı oldu.")
                        return
                    else:
                        logger.error(f"{attempt+1}. denemede bonus URL çağrısı başarısız. Durum kodu: {resp.status}. Yanıt: {response_text}")
        except Exception as e:
            logger.error(f"{attempt+1}. denemede bonus URL çağrısında hata: {e}", exc_info=True)
        if attempt < max_attempts - 1:
            await asyncio.sleep(1)
    logger.error("Bonus URL çağrısı maksimum deneme sayısına ulaştı ve başarısız oldu.")

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.
    """
    full_text = update.message.text
    last_line = full_text.strip().split('\n')[-1].strip()
    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

    user = update.effective_user

    valid, message = await is_valid_username(username)
    if not valid:
        await update.message.reply_text(message)
        context.user_data['awaiting_username'] = False
        return

    unique_code = generate_unique_code()

    try:
        # DB insert'i ayrı thread'de
        await asyncio.to_thread(insert_username_to_db, user.id, username, unique_code)

        # URL kodlaması
        encoded_username = username if "@" in username else quote(username)
        encoded_unique_code = quote(unique_code)

        await update.message.reply_text(
            f'✅ Tebrikler {username}, kullanıcı adınıza deneme bonusu tanımlandı!\n'
            f'İstinye bol şanslar diler.'
        )

        link = f"https://bonus.istinyecasinoortaklik.com/?username={encoded_username}&uni_code={encoded_unique_code}"
        asyncio.create_task(call_bonus_url(link))

        context.user_data['awaiting_username'] = False
    except mysql.connector.IntegrityError as e:
        # UNIQUE ihlali varsa kullanıcıya bilgi ver
        await update.message.reply_text(
            "Bu kullanıcı adıyla daha önce deneme bonusu tanımlanmış görünüyor. "
            "Yatırım bonuslarımızdan yararlanabilirsiniz."
        )
        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:
    user = update.effective_user
    user_id = user.id
    lock = get_user_lock(user_id)

    # Eğer zaten bu kullanıcı için bir işlem çalışıyorsa, yeni tetikleme yapmayalım
    if lock.locked():
        # Sadece bilgi mesajı ver, yeni iş BAŞLATMA
        await update.message.reply_text("⏳ İşleminiz sürüyor, lütfen bekleyiniz.")
        return

    # Username beklemiyoruz ise önce abonelik kontrolü + prompt
    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)
            )
            # Artık bir sonraki mesaj username olacak
            context.user_data['awaiting_username'] = True
        else:
            reply_markup = InlineKeyboardMarkup([
                [InlineKeyboardButton("Kanala Abone Olmak İçin Tıklayınız", url="https://t.me/istinyecasinoresmi")]
            ])
            await update.message.reply_text('Lütfen önce kanala abone olun!', reply_markup=reply_markup)
    else:
        # Username bekleniyor: İlk gelen mesaja işi verip beklemeyi kapat
        # (Kullanıcı arka arkaya yazsa bile yalnızca ilki işlenecek)
        context.user_data['awaiting_username'] = False

        async def runner():
            async with lock:
                try:
                    await save_username(update, context)
                finally:
                    # İş bitince tekrar username isteyebilmesi için açık bırakıyoruz (tercihe göre kapalı da kalabilir)
                    context.user_data['awaiting_username'] = False

        # Tek bir görev başlat
        asyncio.create_task(runner())

def main() -> None:
    application = Application.builder().token("7648388394:AAE3Ih_I2MeCBm4CBzwZ1kpFmF7gjQKirVw").build()

    # Sadece metinleri almak istersen filters.TEXT & ~filters.COMMAND daha güvenli olur,
    # ama mevcut ALL akışını bozmayalım:
    application.add_handler(MessageHandler(filters.ALL, handle_message))

    application.add_error_handler(error_handler)
    application.run_polling()

if __name__ == '__main__':
    main()
