import requests
import time
import json

TOKEN = "8308108880:AAGgK0hmpLmn0Q_2GU7DEC8nFlC02gwv72w"
BASE_URL = f"https://api.telegram.org/bot{TOKEN}"
CHANNEL = "@rakewinresmi"
LOG_FILE = "usernames.txt"

waiting_username = set()
last_update_id = None


def get_updates():
    global last_update_id
    params = {"timeout": 30}
    if last_update_id is not None:
        params["offset"] = last_update_id + 1

    try:
        resp = requests.get(BASE_URL + "/getUpdates", params=params, timeout=40)
        data = resp.json()
    except Exception as e:
        print("getUpdates hata:", e)
        return []

    if not data.get("ok"):
        print("getUpdates ok=False:", data)
        return []

    updates = data.get("result", [])
    if updates:
        last_update_id = updates[-1]["update_id"]
    return updates


def send_message(chat_id, text, reply_markup=None):
    payload = {"chat_id": chat_id, "text": text}
    if reply_markup is not None:
        payload["reply_markup"] = json.dumps(reply_markup)
    try:
        requests.post(BASE_URL + "/sendMessage", data=payload, timeout=20)
    except Exception as e:
        print("sendMessage hata:", e)


def answer_callback_query(callback_query_id, text=None):
    payload = {"callback_query_id": callback_query_id}
    if text:
        payload["text"] = text
    try:
        requests.post(BASE_URL + "/answerCallbackQuery", data=payload, timeout=20)
    except Exception as e:
        print("answerCallbackQuery hata:", e)


def check_channel_member(user_id):
    try:
        resp = requests.get(
            BASE_URL + "/getChatMember",
            params={"chat_id": CHANNEL, "user_id": user_id},
            timeout=20,
        )
        data = resp.json()
        if not data.get("ok"):
            print("getChatMember ok=False:", data)
            return False

        status = data["result"]["status"]
        return status in ("member", "administrator", "creator")
    except Exception as e:
        print("getChatMember hata:", e)
        return False


# 🎛 ANA MENÜ
def send_main_menu(chat_id, first_name=None):
    name_part = first_name if first_name else "Rakewin üyesi"
    text = (
        f"🎉 Hoşgeldin {name_part}! 🎉\n\n"
        "Ana menüden istediğin işlemi seçebilirsin 👇"
    )

    keyboard = {
        "inline_keyboard": [
            [
                {
                    "text": "🎁 Deneme Bonusu Al",
                    "callback_data": "menu_deneme",
                }
            ],
            [
                {
                    "text": "📺 Rakewin TV",
                    "url": "https://rakewin.tv/",
                },
                {
                    "text": "🎯 Promosyonlar",
                    "url": "http://l4f.com/05CZG",
                },
            ],
            [
                {
                    "text": "💰 Para Yatır",
                    "url": "https://t2m.io/Rakewinbot",
                },
                {
                    "text": "💸 Para Çek",
                    "url": "https://t2m.io/Rakewinbot",
                },
            ],
            [
                {
                    "text": "💬 Canlı Destek",
                    "url": "https://t2m.io/Rakewinbot",
                }
            ],
        ]
    }

    send_message(chat_id, text, reply_markup=keyboard)


def handle_message(message):
    chat_id = message["chat"]["id"]
    user = message.get("from", {})
    user_id = user.get("id")
    text = message.get("text", "")

    # /start
    if text == "/start":
        keyboard = {
            "inline_keyboard": [
                [
                    {
                        "text": "✅ Katıldım, Kontrol Et",
                        "callback_data": "check_channel",
                    }
                ]
            ]
        }

        send_message(
            chat_id,
            "❗️ Lütfen önce kanalımıza katılın:\n\n"
            "https://t.me/rakewinresmi",
            reply_markup=keyboard,
        )
        return

    else:
        # Kullanıcı adını bekliyorsak
        if user_id in waiting_username:
            username = text.strip()
            with open(LOG_FILE, "a", encoding="utf-8") as f:
                f.write(
                    f"telegram_id={user_id} | telegram=@{user.get('username')} | site_username={username}\n"
                )

            waiting_username.remove(user_id)

            keyboard_finish = {
                "inline_keyboard": [
                    [
                        {
                            "text": "Deneme Bonusunu Al ✅",
                            "url": "http://l4f.com/05CZG",
                        }
                    ]
                ]
            }

            send_message(
                chat_id,
                "Kayıt tamamlandı 🎉\n\n"
                "Şimdi aşağıdaki butona tıklayarak siteye giriş yapın ve "
                "BONUS TALEP alanından Deneme Bonusu talebinizi oluşturun 👇\n\n"
                "IP çakışması ve güvenlik problemi yoksa deneme bonusunuz "
                "sistem tarafından otomatik olarak tanımlanacaktır.",
                reply_markup=keyboard_finish,
            )


def handle_callback_query(callback_query):
    data = callback_query.get("data")
    cq_id = callback_query.get("id")
    message = callback_query.get("message")
    user = callback_query.get("from", {})
    user_id = user.get("id")
    chat_id = message["chat"]["id"]

    if data == "check_channel":
        in_channel = check_channel_member(user_id)
        if in_channel:
            # ✅ Kanala üye -> mesaj + ana menü
            answer_callback_query(cq_id, "Kanal takibi başarılı! Devam edelim 👇")
            send_message(chat_id, "✅ Kanal takibi başarılı! Devam edelim 👇")
            send_main_menu(chat_id, first_name=user.get("first_name"))
        else:
            answer_callback_query(cq_id, "Kanal üyesi değilsiniz ❗")
            send_message(
                chat_id,
                "❗ Henüz kanal üyesi görünmüyorsunuz.\n"
                "@rakewinresmi kanalına katılıp tekrar deneyin.",
            )

    # 🎁 Menü → Deneme Bonus
    elif data == "menu_deneme":
        waiting_username.add(user_id)
        answer_callback_query(cq_id)
        send_message(
            chat_id,
            "Deneme bonusu için sitede kullandığın kullanıcı adını yaz lütfen.\n"
            "Örn: emre123",
        )


def main_loop():
    print("Bot çalışıyor... CTRL+C ile durdurabilirsiniz.")
    while True:
        updates = get_updates()
        for upd in updates:
            if "message" in upd:
                handle_message(upd["message"])
            if "callback_query" in upd:
                handle_callback_query(upd["callback_query"])
        time.sleep(1)


if __name__ == "__main__":
    main_loop()
