import logging
import re
import urllib.parse
import requests
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__)

async def tel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat_id = update.effective_chat.id

    # 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

    # 3) Bilgilendirme mesajı
    await context.bot.send_message(
        chat_id=chat_id,
        text=f"{len(usernames)} kullanıcı için yatırım bilgileri sorgulanıyor.. 🔍\n" +
             ", ".join(usernames)
    )

    # 4) PHP endpoint'e tek seferde tüm kullanıcıları yolla
    param = urllib.parse.quote(",".join(usernames))
    url = f"http://telegram.istinyecasinoortaklik.com/anasayfa/telegramyenibot?username={param}"

    try:
        resp = requests.get(url, timeout=90)
        resp.raise_for_status()
    except Exception as e:
        logger.error("PHP isteğinde hata", exc_info=e)
        await context.bot.send_message(chat_id=chat_id, text=f"Sunucu hatası: {e}")
        return

    # 5) Gelen metni: "\n\n---\n\n" benzeri ayırıcılardan temiz bir şekilde böl
    parts = re.split(r'\n*-{3,}\n*', resp.text)
    for part in parts:
        part = part.strip()
        if not part:
            continue
        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: %s", send_err, exc_info=send_err)
            # Burada kullanıcıya tekrar mesaj atmıyoruz, sadece logluyoruz

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("7909778509:AAFwy65lc5kzOI0nY2CN7CgkXBSzbZkDIi8")
        .build()
    )
    app.add_handler(CommandHandler("tel", tel))
    app.add_error_handler(error_handler)
    app.run_polling()
