import telebot
import logging
import time
import re

logging.basicConfig(
    filename="shop_bot.log",
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)

TOKEN = "8758267039:AAFSpf3PS8tIm_OT3IbIS7Za6qwFi4R4xBE"
bot = telebot.TeleBot(TOKEN)
CHANNEL_ID = "@eFootball_Hub_IR"

last_global_reply_time = 0
GLOBAL_COOLDOWN = 30 * 60          
user_cooldowns = {}
USER_COOLDOWN_DURATION = 3 * 24 * 60 * 60  

GROUP_REPLY_TEXT = (
    "■ کاربر محترم، می‌خواهی اطلاعات اکانتت را بدی و آن را در کانال شاپ قرار دهم؟\n"
    "مثلاً: سکه، ریجن، تعداد لوگ و...\n\n"
    "مدیر و توسعه‌دهنده: فردین فرهادی\n"
    "ID Channel: @eFootball_Hub_IR"
)

@bot.message_handler(commands=['start'])
def send_welcome(message):
    if message.chat.type == 'private':
        bot.send_message(message.chat.id, "سلام فردین عزیز، ربات شاپ با موفقیت راه‌اندازی شد 🌹")

@bot.message_handler(content_types=['text', 'photo'])
def shop_form_handler(message):
    global last_global_reply_time
    
    if message.chat.type not in ['group', 'supergroup']:
        return

    if message.from_user.is_bot:
        return

    user_id = message.from_user.id
    current_time = time.time()

    if user_id in user_cooldowns:
        if current_time - user_cooldowns[user_id] < USER_COOLDOWN_DURATION:
            return  

    text = message.text if message.text else (message.caption if message.caption else "")
    text_norm = text.replace('ي', 'ی').replace('ك', 'ک').lower()
    
    words = text_norm.split()
    has_exact_foroush = "فروش" in words  
    has_taagh = "طاق" in words          
    has_digit = bool(re.search(r'[0-9]', text_norm))
    has_question_mark = "?" in text or "؟" in text

    is_valid_spec = False

    if message.photo:
        is_valid_spec = True
    else:
        is_taagh_question = has_taagh and has_question_mark and not has_digit and not has_exact_foroush
        is_foroush_question = has_exact_foroush and has_question_mark and not has_digit and not has_taagh

        if is_taagh_question or is_foroush_question:
            is_valid_spec = False
        else:
            is_only_taagh = has_taagh and not has_question_mark
            is_only_foroush = (len(words) == 1 and words[0] == "فروش") and not has_question_mark
            has_keyword = ("فروش" in text_norm) or ("طاق" in text_norm)
            is_keyword_with_digit = has_keyword and has_digit
            is_foroush_with_taagh = ("فروش" in text_norm) and has_taagh

            if is_only_taagh or is_only_foroush or is_keyword_with_digit or is_foroush_with_taagh:
                is_valid_spec = True
            else:
                is_valid_spec = False

    if is_valid_spec:
        if current_time - last_global_reply_time < GLOBAL_COOLDOWN:
            return

        user_name = message.from_user.first_name
        user_username = f"@{message.from_user.username}" if message.from_user.username else "ندارد"

        try:
            formatted_form = (
                f"🛒 **فرم جدید ثبت مشخصات و معامله**\n\n"
                f"👤 **فروشنده / ارسال‌کننده:** {user_name}\n"
                f"🔗 **یوزرنیم:** {user_username}\n"
                f"🆔 **آیدی عددی:** `{user_id}`\n\n"
                f"📋 **جزئیات و مشخصات اکانت:**\n"
                f"-----------------------------------\n"
                f"{text if text else '[ارسال تصویر مشخصات]'}\n"
                f"-----------------------------------\n\n"
                f"🛡 **وضعیت:** در حال بررسی واسطه\n"
                f"مدیریت و واسطه: فردین فرهادی\n"
                f"ID Channel: @eFootball_Hub_IR"
            )

            if message.photo:
                photo_file_id = message.photo[-1].file_id
                bot.send_photo(CHANNEL_ID, photo_file_id, caption=formatted_form, parse_mode="Markdown")
            else:
                bot.send_message(CHANNEL_ID, formatted_form, parse_mode="Markdown")

            bot.reply_to(message, GROUP_REPLY_TEXT)
            
            last_global_reply_time = current_time
            user_cooldowns[user_id] = current_time
            
        except Exception as e:
            logging.error(f"Error in shop bot submission: {e}")

def run_bot():
    while True:
        try:
            logging.info("24/7 Persistent Shop Bot starting polling loop...")
            bot.infinity_polling(
                timeout=60,
                long_polling_timeout=60,
                skip_pending=True,
                allowed_updates=["message"]
            )
        except Exception as e:
            logging.exception(f"Critical polling exception caught: {e}")
            print(f"Bot crashed with error: {e}. Restarting in 5 seconds...")
            time.sleep(5)
        else:
            logging.warning("Polling stream disconnected gracefully. Reconnecting...")
            time.sleep(3)

if __name__ == "__main__":
    run_bot()
    