import logging
import re
import urllib.parse
import requests
import asyncio
from telegram import Update
from telegram.ext import (
    ApplicationBuilder,
    CommandHandler,
    ContextTypes,
)

# Logging ayarları
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)
logger = logging.getLogger(__name__)

BATCH_SIZE = 50           # 50-50 böl
BATCH_DELAY_SEC = 20     # her batch arası küçük bekleme (gerekirse arttır)

ALLOWED_CHAT_ID = -1003158585338  # /tel komutunun çalışacağı tek grup

def chunk_list(items, size):
    for i in range(0, len(items), size):
        yield items[i:i+size]

async def tel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat_id = update.effective_chat.id

    # SADECE BELİRLİ GRUPTA ÇALIŞSIN
    if chat_id != ALLOWED_CHAT_ID:
        # İstersen tamamen sessiz olsun dersen burayı boş return yapabilirsin
        await context.bot.send_message(
            chat_id=chat_id,
            text="Bu komut sadece yetkili grupta kullanılabilir."
        )
        return

    # 1) Kullanıcı adı argümanları yoksa uyar
    if not context.args:
        await context.bot.send_message(
            chat_id=chat_id,
            text=(
                "Kullanım:\n"
                "/tel kullanıcı1 kullanıcı2 ...\n"
                "veya\n"
                "/tel kullanıcı1,kullanıcı2,..."
            )
        )
        return

    # 2) Argümanları virgül, noktalı virgül veya boşlukla ayır
    raw = " ".join(context.args).strip()
    usernames = [u.strip() for u in re.split(r'[\s,;]+', raw) if u.strip()]
    if not usernames:
        await context.bot.send_message(chat_id=chat_id, text="Lütfen en az bir geçerli kullanıcı adı girin.")
        return

    total = len(usernames)
    await context.bot.send_message(
        chat_id=chat_id,
        text=f"{total} kullanıcı için yatırım bilgileri 50'lik paketler halinde sorgulanıyor.. 🔍"
    )

    # 3) 50-50 böl ve her batch için ayrı istek at
    batch_index = 0
    for batch in chunk_list(usernames, BATCH_SIZE):
        batch_index += 1
        start = (batch_index - 1) * BATCH_SIZE + 1
        end = min(batch_index * BATCH_SIZE, total)

        # Bilgilendirme
        await context.bot.send_message(
            chat_id=chat_id,
            text=f"📦 Paket {batch_index}: {start}-{end} arası kullanıcılar sorgulanıyor..."
        )

        # 4) PHP endpoint'e bu batch'i gönder
        try:
            param = urllib.parse.quote(",".join(batch))
            url = f"https://hanedanbet.app/anasayfa/telegramyenibott?username={param}"

            # Not: requests senkron; handler içinde kısa bloklarımız var, sorun olmaz.
            resp = requests.get(url, timeout=90)
            resp.raise_for_status()

        except Exception as e:
            logger.error("PHP isteğinde hata (batch %s): %s", batch_index, e, exc_info=e)
            await context.bot.send_message(
                chat_id=chat_id,
                text=f"❌ Paket {batch_index} hata verdi: {e}"
            )
            # Sonraki batch'e devam
            await asyncio.sleep(BATCH_DELAY_SEC)
            continue

        # 5) Gelen metni ayır ve gönder
        text = resp.text or ""
        parts = re.split(r'\n*-{3,}\n*', text)  # "---" benzeri ayraçlara göre böl
        sent_any = False
        for part in parts:
            part = part.strip()
            if not part:
                continue
            sent_any = True
            try:
                await context.bot.send_message(
                    chat_id=chat_id,
                    text=part,
                    parse_mode='HTML',
                    disable_web_page_preview=True
                )
            except Exception as send_err:
                logger.warning("Mesaj gönderilirken hata (batch %s): %s", batch_index, send_err, exc_info=send_err)

        if not sent_any:
            # Sunucu bir şey döndürmediyse kısa bilgi geç
            await context.bot.send_message(
                chat_id=chat_id,
                text=f"ℹ️ Paket {batch_index} için sonuç bulunamadı veya boş yanıt geldi."
            )

        # 6) Batch'ler arası ufak bekleme (rate-limit ve GET sınırları için iyi olur)
        await asyncio.sleep(BATCH_DELAY_SEC)

    await context.bot.send_message(
        chat_id=chat_id,
        text="✅ Tüm paketlerin sorgusu tamamlandı."
    )

async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
    logger.error("Yakalanmamış hata:", exc_info=context.error)
    if isinstance(update, Update) and update.effective_chat:
        try:
            await context.bot.send_message(
                chat_id=update.effective_chat.id,
                text="Üzgünüm, bir hata oluştu. Lütfen tekrar deneyin."
            )
        except:
            pass

if __name__ == '__main__':
    app = (
        ApplicationBuilder()
        .token("8484233300:AAEm0wdh5JaBzdRBHdz3KgQvvL5yixdaT_s")
        .build()
    )
    app.add_handler(CommandHandler("tel", tel))
    app.add_error_handler(error_handler)
    app.run_polling()
