import logging
import random
import string
import asyncio
from datetime import datetime
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, CommandHandler

# MySQL bağlantı bilgilerini ayarlayın
db_config = {
    'user': 'playmenbonus_db',
    'password': '34trabzon61',
    'host': '213.136.71.24',
    'database': 'playmenbonus_db'
}

# 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://playmenbonus.net/gunluk-fs/"

# Engellenecek grup chat ID'si
EXCLUDED_CHAT_ID = -1002401950371

# --- 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)

# --- Güvenli reply helper fonksiyonu ---
async def safe_reply(update: Update, context: CallbackContext, text: str, **kwargs) -> None:
    chat_id = update.effective_chat.id if update.effective_chat else None
    if chat_id == EXCLUDED_CHAT_ID:
        return
    await update.message.reply_text(text, **kwargs)

# --- Global Error Handler ---
async def error_handler(update: object, context: CallbackContext) -> None:
    logger.error("Exception while handling an update:", exc_info=context.error)

# --- Fonksiyonlar ---

async def check_subscription(update: Update, context: CallbackContext) -> bool:
    user_id = update.effective_user.id
    channel_id = EXCLUDED_CHAT_ID
    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

def generate_unique_code(length=8):
    characters = string.ascii_letters + string.digits
    return ''.join(random.choice(characters) for _ in range(length))

# --- Veritabanı işlemleri için yardımcı fonksiyonlar ---

def has_claimed_today(username):
    """fs_users.tarih sütununa bakar; aynı gün içinde talep varsa True döner."""
    try:
        conn = pool.get_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT tarih FROM fs_users WHERE username = %s", (username,))
        row = cursor.fetchone()
        cursor.close()
        conn.close()

        if not row or row[0] is None:
            return False
        return row[0].date() == datetime.now().date()
    except Error as e:
        logger.error(f"DB Error in has_claimed_today: {e}", exc_info=True)
        # Hata durumunda güvenlik nedeniyle engelle
        return True

def insert_username_to_db(user_id, username, unique_code):
    """fs_users tablosuna ekler veya tarih ile unique_code'u günceller."""
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    try:
        conn = pool.get_connection()
        cursor = conn.cursor()
        cursor.execute("""
            INSERT INTO fs_users (user_id, username, unique_code, tarih)
            VALUES (%s, %s, %s, %s)
            ON DUPLICATE KEY UPDATE
              unique_code = VALUES(unique_code),
              tarih       = VALUES(tarih)
        """, (user_id, username, unique_code, now))
        conn.commit()
        cursor.close()
        conn.close()
    except Error as e:
        logger.error(f"Error inserting/updating DB: {e}", exc_info=True)
        raise

# --- Asenkron doğrulama ve kayıt işlemleri ---

async def is_valid_username(username):
    # 1) Bugün talep yapmış mı?
    if await asyncio.to_thread(has_claimed_today, username):
        return False, "Freespin bonusunu bugün için zaten kullandınız."

    # 2) Dış servis doğrulaması
    url = f"{verification_url}{username if '@' in username else quote(username)}"
    try:
        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 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:
                    if resp.status == 200:
                        logger.info(f"Bonus URL çağrısı {attempt+1}. denemede başarılı oldu: {link}")
                        return
        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(f"Bonus URL çağrısı maksimum deneme sayısına ulaştı: {link}")

async def save_username(update: Update, context: CallbackContext) -> None:
    full_text = update.message.text
    last_line = full_text.strip().split('\n')[-1].strip()
    if len(last_line) > 1 and ((last_line[0] in "\"'") and (last_line[-1] in "\"'")):
        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 safe_reply(update, context, message)
        context.user_data['awaiting_username'] = False
        return

    unique_code = generate_unique_code()
    try:
        await asyncio.to_thread(insert_username_to_db, user.id, username, unique_code)

        encoded_username = username if "@" in username else quote(username)
        encoded_unique_code = quote(unique_code)

        await safe_reply(update, context,
            f'✅ Tebrikler {username}, Telegram 20 Freespin Hediye bonusu tanımlandı!\n'
            'Playmen bol şanslar diler.'
        )

        link = f"https://playmenbonus.net/?username={encoded_username}&fs_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 safe_reply(update, context, f"Bir hata oluştu: {e}")
        context.user_data['awaiting_username'] = False

# --- Bonus türünü seçmek için komut işlemcisi ---
async def start_freespin(update: Update, context: CallbackContext) -> None:
    if update.effective_chat.id == EXCLUDED_CHAT_ID:
        return
    if await check_subscription(update, context):
        await safe_reply(update, context,
            'Telegram 20 Freespin Hediye bonusu için kullanıcı adınızı yazın:',
            reply_markup=ForceReply(selective=True)
        )
        context.user_data['awaiting_username'] = True
    else:
        reply_markup = InlineKeyboardMarkup([
            [InlineKeyboardButton("Kanala Abone Olmak İçin Tıklayınız", url="https://t.me/playmenclub")]
        ])
        await safe_reply(update, context, 'Lütfen önce kanala abone olun!', reply_markup=reply_markup)

# --- Genel mesaj işleyici ---
async def handle_message(update: Update, context: CallbackContext) -> None:
    if update.effective_chat.id == EXCLUDED_CHAT_ID:
        return
    if context.user_data.get('awaiting_username'):
        asyncio.create_task(save_username(update, context))
    else:
        await safe_reply(update, context, 'Bonus almak için /freespin komutunu kullanın.')

def main() -> None:
    application = Application.builder().token("8169965666:AAF48CXNE_PjmetSttEAvQ6DbibeQUjpK4g").build()

    application.add_handler(CommandHandler('freespin', start_freespin))
    application.add_handler(MessageHandler(filters.ALL, handle_message))
    application.add_error_handler(error_handler)

    application.run_polling()

if __name__ == '__main__':
    main()
