import random
import time
import requests

# --- AYARLAR ---
BOT_TOKEN = "7727629734:AAH-yfMJwEW0XTqabwU4Gyv0NsWfAxe93eQ"
CHAT_ID   = "-1002632873993"
MIN_DELAY = 1800    # 30dk
MAX_DELAY = 7200    # 2sa

API_URL = f"https://api.telegram.org/bot{BOT_TOKEN}/"

# --- MESAJ & ANKETLERİ YÜKLE ---
def load_texts(*files):
    msgs = []
    for fn in files:
        with open(fn, encoding="utf-8") as f:
            msgs += [l.strip() for l in f if l.strip()]
    return msgs

def load_polls(fn):
    """
    - Soru satırı: '?' ile bitiyor.
    - Seçenekler: boş satırlar atlanarak,
      soru satırından sonra gelen tüm dolu satırlar,
      ta ki bir boş satır ya da bir sonraki soru gelene kadar.
    """
    polls = []
    with open(fn, encoding="utf-8") as f:
        lines = [l.rstrip() for l in f]
    i = 0
    while i < len(lines):
        line = lines[i].strip()
        if line.endswith("?"):
            question = line
            i += 1
            # boş satırları atla
            while i < len(lines) and lines[i].strip() == "":
                i += 1
            options = []
            # boş olmayan satırlar veya yeni soru görünce dur
            while i < len(lines) and lines[i].strip() != "" and not lines[i].strip().endswith("?"):
                options.append(lines[i].strip())
                i += 1
            if len(options) >= 2:
                polls.append((question, options))
            continue
        i += 1
    return polls

# düz metinler
TEXT_MESSAGES = load_texts(
    "centilmenlik-tuyolari.txt",
    "gunluk-slot-tuyolari.txt"
)
# anketler
POLL_QUESTIONS = load_polls("anketler-ve-minitestler.txt")

print(f"[DEBUG] Yüklenen düz mesaj sayısı: {len(TEXT_MESSAGES)}")
print(f"[DEBUG] Yüklenen anket sayısı: {len(POLL_QUESTIONS)}")

ALL_ITEMS = TEXT_MESSAGES + POLL_QUESTIONS

def send_message(text):
    resp = requests.post(API_URL + "sendMessage",
                         data={"chat_id": CHAT_ID, "text": text})
    if not resp.ok:
        print(f"[ERROR] sendMessage {resp.status_code} {resp.text}")

def send_poll(question, options):
    resp = requests.post(API_URL + "sendPoll", json={
        "chat_id": CHAT_ID,
        "question": question,
        "options": options,
        "is_anonymous": False,
        "allows_multiple_answers": False
    })
    if not resp.ok:
        print(f"[ERROR] sendPoll {resp.status_code} {resp.text}")

def main():
    previous_item = None
    while True:
        item = random.choice(ALL_ITEMS)
        # eğer öncekiyle aynıysa tekrar seç
        if item == previous_item:
            continue
        previous_item = item

        if isinstance(item, tuple):
            q, opts = item
            print(f"[DEBUG] Poll: {q} -> {opts}")
            send_poll(q, opts)
        else:
            print(f"[DEBUG] Msg : {item[:30]}...")
            send_message(item)

        wait = random.randint(MIN_DELAY, MAX_DELAY)
        print(f"[DEBUG] {wait}s sleep")
        time.sleep(wait)

if __name__ == "__main__":
    main()
