import time
import re
import json
import random
import os
import jdatetime
import datetime as dt
import sqlite3
import fcntl
import requests
import shutil
from datetime import datetime
from config import OWNER_ID

ENABLED_FLAG = 8

LOCK_COLUMNS = [
    'link', 'forward', 'edit', 'photo', 'video', 'file', 'zip', 'number',
    'music', 'voice', 'mention', 'repetition',
    'sticker', 'hashtag', 'code', 'swear', 'poll', 'story', 'location', 'live'
]

LOCK_NAMES_PERSIAN = [
    'لینک', 'فوروارد', 'ویرایش', 'عکس', 'فیلم', 'فایل', 'زیپ', 'عدد',
    'آهنگ', 'ویس', 'آیدی', 'کد هنگی',
    'استیکر', 'هشتگ', 'کد', 'فحاشی', 'نظرسنجی', 'استوری', 'لوکیشن', 'پخش زنده'
]
RESPONSES_FILE = "/home/rezair/public_html/rub/responses.json"
RESPONSES_BACKUP_FILE = "/home/rezair/public_html/rub/responses_backup.json"
FUN_CACHE_FILE = "/home/rezair/public_html/rub/fun_cache.json"
TRUTHS_FILE = "/home/rezair/public_html/rub/truths.json"
DARES_FILE = "/home/rezair/public_html/rub/dares.json"


def load_json_list(file_path):
    """بارگذاری یک لیست از فایل JSON"""
    try:
        if os.path.exists(file_path):
            with open(file_path, "r", encoding="utf-8") as f:
                data = json.load(f)
                if isinstance(data, list) and data:
                    return data
    except Exception as e:
        log_message(f"❌ خطا در بارگذاری {file_path}: {e}", "ERROR")
    return None

def get_random_truth():
    """دریافت یک حقیقت تصادفی از فایل"""
    truths = load_json_list(TRUTHS_FILE)
    if truths:
        return random.choice(truths)
    return "خطا در دریافت حقیقت. لطفاً دوباره تلاش کنید."

def get_random_dare():
    """دریافت یک جرئت تصادفی از فایل"""
    dares = load_json_list(DARES_FILE)
    if dares:
        return random.choice(dares)
    return "خطا در دریافت جرئت. لطفاً دوباره تلاش کنید."
    
def load_responses():
    try:
        if os.path.exists(RESPONSES_FILE):
            with open(RESPONSES_FILE, "r", encoding="utf-8") as f:
                return json.load(f)
        return {}
    except:
        return {}

def get_ai_response(text):
    responses = load_responses()
    if not responses:
        return None
    
    text_lower = text.strip().lower()
    
    if text_lower in responses:
        return random.choice(responses[text_lower])
    
    return None
def load_responses():
    """بارگذاری پاسخ‌ها از فایل JSON با مدیریت خطا و بکاپ"""
    try:
        if os.path.exists(RESPONSES_FILE):
            with open(RESPONSES_FILE, "r", encoding="utf-8") as f:
                fcntl.flock(f, fcntl.LOCK_SH) 
                data = json.load(f)
                fcntl.flock(f, fcntl.LOCK_UN)
                return data
        return {}
    except json.JSONDecodeError as e:
        log_message(f"❌ خطا در دیکد JSON: {e}", "ERROR")
        if os.path.exists(RESPONSES_BACKUP_FILE):
            try:
                with open(RESPONSES_BACKUP_FILE, "r", encoding="utf-8") as f:
                    data = json.load(f)
                log_message("✅ فایل responses.json از بکاپ بازیابی شد", "INFO")
                shutil.copy(RESPONSES_BACKUP_FILE, RESPONSES_FILE)
                return data
            except:
                pass
        return {}
    except Exception as e:
        log_message(f"❌ خطا در بارگذاری responses.json: {e}", "ERROR")
        return {}

def save_responses(data):
    """ذخیره دیکشنری پاسخ‌ها در فایل JSON با بکاپ و قفل"""
    try:
        os.makedirs(os.path.dirname(RESPONSES_FILE), exist_ok=True)
        
        if os.path.exists(RESPONSES_FILE):
            shutil.copy(RESPONSES_FILE, RESPONSES_BACKUP_FILE)
        
        temp_file = RESPONSES_FILE + ".tmp"
        with open(temp_file, "w", encoding="utf-8") as f:
            fcntl.flock(f, fcntl.LOCK_EX)  
            json.dump(data, f, ensure_ascii=False, indent=4)
            fcntl.flock(f, fcntl.LOCK_UN)
        
        shutil.move(temp_file, RESPONSES_FILE)
        log_message(f"✅ responses.json با {len(data)} کلید ذخیره شد", "INFO")
        return True
    except Exception as e:
        log_message(f"❌ خطا در ذخیره responses.json: {e}", "ERROR")
        if os.path.exists(RESPONSES_BACKUP_FILE):
            shutil.copy(RESPONSES_BACKUP_FILE, RESPONSES_FILE)
        return False

def learn_response(question, answer):
    """اضافه کردن سوال و جواب جدید با مدیریت خطا"""
    try:
        responses = load_responses()
        question_lower = question.strip().lower()
        answer = answer.strip()
        
        if not question_lower or not answer:
            return False, "سوال و جواب نمی‌توانند خالی باشند."
        
        if question_lower in responses:
            if answer not in responses[question_lower]:
                responses[question_lower].append(answer)
                if save_responses(responses):
                    return True, f"حله"
                else:
                    return False, "خطا"
            else:
                return False, f"این که قبلا بود"
        else:
            responses[question_lower] = [answer]
            if save_responses(responses):
                return True, f"حله"
            else:
                return False, "خطا"
    except Exception as e:
        return False, f"خطا {str(e)}"

def forget_response(question, answer=None):

    try:
        responses = load_responses()
        question_lower = question.strip().lower()
        
        if question_lower not in responses:
            return False, f"نداریم که"
        
        if answer is None:
            del responses[question_lower]
            save_responses(responses)
            return True, f"حله"
        else:
            answer = answer.strip()
            if answer not in responses[question_lower]:
                return False, f"نداریم که"
            
            responses[question_lower].remove(answer)
            if not responses[question_lower]:
                del responses[question_lower]
                save_responses(responses)
                return True, f"حله"
            else:
                save_responses(responses)
                return True, f"حله"
    except Exception as e:
        log_message(f" خطا در forget_response: {e}", "ERROR")
        return False, f" خطا در فراموشی: {str(e)}"

def load_fun_cache():
    try:
        if os.path.exists(FUN_CACHE_FILE):
            with open(FUN_CACHE_FILE, "r", encoding="utf-8") as f:
                data = json.load(f)
                for key, value in data.items():
                    if not isinstance(value, list):
                        data[key] = [value]
                return data
    except:
        pass
    return {}

def save_fun_cache(data):
    try:
        os.makedirs(os.path.dirname(FUN_CACHE_FILE), exist_ok=True)
        with open(FUN_CACHE_FILE, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
        return True
    except:
        return False

def get_fun_api(categorie):
    category_key = categorie.strip()
    url = "https://l8pStudio.ir/apis-loop/api-fun.php"
    categories = {
        "جوک": "jock",
        "حدیث": "hadis",
        "فال": "fal",
        "فکت": "fact",
        "دعا": "doa",
        "دانستنی": "dnstni",
        "دقت": "deghat",
        "داستان": "dastan",
        "چیستان": "chistan",
        "بیو": "bio",
        "انگیزشی": "angizeshi",
        "خاطره": "khatereh",
        "خطبه": "khotbeh",
        "پ ن پ": "pnp",
        "تکست": "text",
        "چالش": "chalesh"
    }

    if category_key not in categories:
        return "دسته‌بندی نامعتبر است."

    api_success = False
    new_content = None
    error_msg = None

    try:
        payload = {"category": categories[category_key]}
        response = requests.post(url, json=payload, timeout=10)
        if response.status_code == 200:
            data = response.json()
            if data.get("status"):
                new_content = data['data']['content']
                api_success = True
                log_message(f"✅ دریافت موفق از API برای دسته {category_key}", "INFO")
            else:
                error_msg = "API پاسخ ناموفق برگرداند."
        else:
            error_msg = f"API با کد {response.status_code} پاسخ داد."
    except Exception as e:
        error_msg = str(e)
        log_message(f"❌ خطا در تماس با API: {e}", "ERROR")

    cache = load_fun_cache()

    if api_success and new_content:
        if category_key not in cache:
            cache[category_key] = []
        
        if new_content not in cache[category_key]:
            cache[category_key].append(new_content)
            save_fun_cache(cache)
            log_message(f"✅ محتوای جدید به کش اضافه شد (تعداد کل: {len(cache[category_key])})", "INFO")
        else:
            log_message(f"ℹ️ محتوای تکراری بود، اضافه نشد", "DEBUG")
        
        return new_content

    if category_key in cache and cache[category_key]:
        selected = random.choice(cache[category_key])
        log_message(f"⚠️ استفاده از کش برای دسته {category_key} (به‌دلیل خطای API)", "WARNING")
        return selected

    log_message(f"❌ خطا در دریافت محتوا برای دسته {category_key}: {error_msg}", "ERROR")
    return f"خطا در دریافت محتوا. لطفاً دوباره تلاش کنید."
    
def set_chatbot_status(cursor, group_guid, status):
    cursor.execute("""
        INSERT INTO group_settings (group_guid, chatbot, auto_delete, auto_delete_time, default_warning_limit, default_mute_time, group_status)
        VALUES (%s, %s, 0, 0, 3, 3600, 1)
        ON DUPLICATE KEY UPDATE chatbot = %s
    """, (group_guid, status, status))

def get_chatbot_status(cursor, group_guid):
    cursor.execute("SELECT chatbot FROM group_settings WHERE group_guid=%s", (group_guid,))
    row = cursor.fetchone()
    return row[0] if row else 0
    
def log_message(message, level="INFO"):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open("/home/rezair/public_html/rub/bot_log.txt", "a", encoding="utf-8") as log_file:
        log_file.write(f"[{timestamp}] [{level}] {message}\n")
        
def set_lock_by_number(cursor, group_guid, lock_num, status):
    if 1 <= lock_num <= len(LOCK_COLUMNS):
        col = LOCK_COLUMNS[lock_num - 1]
        set_lock(cursor, group_guid, col, status)
        return True
    return False

def init_new_tables(cursor):
    cursor.execute("""CREATE TABLE IF NOT EXISTS user_stats (
        user_guid VARCHAR(64),
        group_guid VARCHAR(64),
        messages_count INT DEFAULT 0,
        today_messages INT DEFAULT 0,
        warnings INT DEFAULT 0,
        medals TEXT,
        level INT DEFAULT 0,
        join_date TEXT,
        last_date TEXT,
        asl TEXT,
        lagab TEXT,
        medal_score INT DEFAULT 0,
        PRIMARY KEY (user_guid, group_guid)
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS message_log (
        message_id VARCHAR(64),
        group_guid VARCHAR(64),
        received_at INT,
        PRIMARY KEY (message_id, group_guid)
    )""")
    cursor.execute("CREATE INDEX IF NOT EXISTS idx_msg_group ON message_log(group_guid)")
    cursor.execute("""CREATE TABLE IF NOT EXISTS mutes (
        user_guid VARCHAR(64),
        group_guid VARCHAR(64),
        until_time INT,
        PRIMARY KEY (user_guid, group_guid)
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS bans (
        user_guid VARCHAR(64),
        group_guid VARCHAR(64),
        banned_at INT,
        PRIMARY KEY (user_guid, group_guid)
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS locks (
        group_guid VARCHAR(64) PRIMARY KEY,
        link INT DEFAULT 0,
        forward INT DEFAULT 0,
        edit INT DEFAULT 0,
        photo INT DEFAULT 0,
        video INT DEFAULT 0,
        file INT DEFAULT 0,
        zip INT DEFAULT 0,
        number INT DEFAULT 0,
        music INT DEFAULT 0,
        voice INT DEFAULT 0,
        mention INT DEFAULT 0,
        repetition INT DEFAULT 0,
        sticker INT DEFAULT 0,
        hashtag INT DEFAULT 0,
        code INT DEFAULT 0,
        swear INT DEFAULT 0,
        poll INT DEFAULT 0,
        story INT DEFAULT 0,
        location INT DEFAULT 0,
        live INT DEFAULT 0
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS group_settings (
        group_guid VARCHAR(64) PRIMARY KEY,
        chatbot INT DEFAULT 0,
        auto_delete INT DEFAULT 0,
        auto_delete_time INT DEFAULT 0,
        default_warning_limit INT DEFAULT 3,
        default_mute_time INT DEFAULT 3600,
        group_status INT DEFAULT 1
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS chatbot (
        question VARCHAR(255) PRIMARY KEY,
        answer TEXT,
        group_guid VARCHAR(64)
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS bot_chats (
        chat_id VARCHAR(64) PRIMARY KEY,
        user_guid VARCHAR(64),
        user_name TEXT,
        start_date INT
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS medals (
        user_guid VARCHAR(64),
        group_guid VARCHAR(64),
        medal_type VARCHAR(50),
        awarded_at INT,
        PRIMARY KEY (user_guid, group_guid, medal_type)
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS allowed_groups (
        group_guid VARCHAR(64) PRIMARY KEY,
        added_by TEXT,
        added_at INT,
        expires_at INT
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS banner (
        id INT PRIMARY KEY CHECK (id = 1),
        source_chat_id TEXT,
        source_message_id TEXT,
        interval_hours INT,
        active INT DEFAULT 0
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS banner_exceptions (
        group_guid VARCHAR(64) PRIMARY KEY
    )""")
def add_allowed_group(cursor, group_guid, owner_guid, days):
    expires_at = int(time.time()) + (days * 86400)
    cursor.execute("REPLACE INTO allowed_groups (group_guid, added_by, added_at, expires_at) VALUES (%s, %s, %s, %s)",
                   (group_guid, owner_guid, int(time.time()), expires_at))
def is_subscription_mode(cursor):
    cursor.execute("SELECT value FROM bot_state WHERE `key`='bot_mode'")
    row = cursor.fetchone()
    return row and row[0] == "subscription"

def set_bot_mode(cursor, mode):
    cursor.execute("REPLACE INTO bot_state (`key`, value) VALUES (%s, %s)", ("bot_mode", mode))
    cursor.connection.commit()   

def set_banner(cursor, source_chat_id, source_message_id, interval_hours):
    cursor.execute("DELETE FROM banner")
    cursor.execute("INSERT INTO banner (id, source_chat_id, source_message_id, interval_hours, active) VALUES (1, %s, %s, %s, 1)",
                   (source_chat_id, source_message_id, interval_hours))

def get_banner(cursor):
    cursor.execute("SELECT source_chat_id, source_message_id, interval_hours, active FROM banner WHERE id=1")
    return cursor.fetchone()

def deactivate_banner(cursor):
    cursor.execute("UPDATE banner SET active=0 WHERE id=1")

def add_banner_exception(cursor, group_guid):
    cursor.execute("INSERT IGNORE INTO banner_exceptions (group_guid) VALUES (%s)", (group_guid,))

def remove_banner_exception(cursor, group_guid):
    cursor.execute("DELETE FROM banner_exceptions WHERE group_guid=%s", (group_guid,))


def convert_to_font_styles(text):
    """
    تبدیل متن انگلیسی و اعداد به چند سبک فونت یونیکد.
    خروجی: لیستی از دیکشنری‌ها با کلیدهای 'style_name' و 'transformed_text'
    """
    persian_digits = '۰۱۲۳۴۵۶۷۸۹'
    arabic_digits = '٠١٢٣٤٥٦٧٨٩'
    english_digits = '0123456789'
    trans_table = str.maketrans(persian_digits + arabic_digits, english_digits + english_digits)
    text = text.translate(trans_table)

    lower_chars = 'abcdefghijklmnopqrstuvwxyz'
    upper_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    digits = '0123456789'

    persian_chars = 'آ ا ب پ ت ث ج چ ح خ د ذ ر ز ژ س ش ص ض ط ظ ع غ ف ق ک گ ل م ن و ه ی'
    persian_list = list(persian_chars.replace(' ', ''))

    styles = {
        "🔤 معمولی": (lower_chars, upper_chars, digits),
        "𝐁𝐨𝐥𝐝": ('𝐚𝐛𝐜𝐝𝐞𝐟𝐠𝐡𝐢𝐣𝐤𝐥𝐦𝐧𝐨𝐩𝐪𝐫𝐬𝐭𝐮𝐯𝐰𝐱𝐲𝐳',
                  '𝐀𝐁𝐂𝐃𝐄𝐅𝐆𝐇𝐈𝐉𝐊𝐋𝐌𝐍𝐎𝐏𝐐𝐑𝐒𝐓𝐔𝐕𝐖𝐗𝐘𝐙',
                  '𝟎𝟏𝟐𝟑𝟒𝟓𝟔𝟕𝟖𝟗'),
        "𝐼𝑡𝑎𝑙𝑖𝑐": ('𝑎𝑏𝑐𝑑𝑒𝑓𝑔ℎ𝑖𝑗𝑘𝑙𝑚𝑛𝑜𝑝𝑞𝑟𝑠𝑡𝑢𝑣𝑤𝑥𝑦𝑧',
                    '𝐴𝐵𝐶𝐷𝐸𝐹𝐺𝐻𝐼𝐽𝐾𝐿𝑀𝑁𝑂𝑃𝑄𝑅𝑆𝑇𝑈𝑉𝑊𝑋𝑌𝑍',
                    '0123456789'),
        "𝑩𝒐𝒍𝒅 𝑰𝒕𝒂𝒍𝒊𝒄": ('𝒂𝒃𝒄𝒅𝒆𝒇𝒈𝒉𝒊𝒋𝒌𝒍𝒎𝒏𝒐𝒑𝒒𝒓𝒔𝒕𝒖𝒗𝒘𝒙𝒚𝒛',
                          '𝑨𝑩𝑪𝑫𝑬𝑭𝑮𝑯𝑰𝑱𝑲𝑳𝑴𝑵𝑶𝑷𝑸𝑹𝑺𝑻𝑼𝑽𝑾𝑿𝒀𝒁',
                          '𝟎𝟏𝟐𝟑𝟒𝟓𝟔𝟕𝟖𝟗'),
        "𝙼𝚘𝚗𝚘𝚜𝚙𝚊𝚌𝚎": ('𝚊𝚋𝚌𝚍𝚎𝚏𝚐𝚑𝚒𝚓𝚔𝚕𝚖𝚗𝚘𝚙𝚚𝚛𝚜𝚝𝚞𝚟𝚠𝚡𝚢𝚣',
                      '𝙰𝙱𝙲𝙳𝙴𝙵𝙶𝙷𝙸𝙹𝙺𝙻𝙼𝙽𝙾𝙿𝚀𝚁𝚂𝚃𝚄𝚅𝚆𝚇𝚈𝚉',
                      '𝟶𝟷𝟸𝟹𝟺𝟻𝟼𝟽𝟾𝟿'),
        "𝔻𝕠𝕦𝕓𝕝𝕖 𝕊𝕥𝕣𝕦𝕔𝕜": ('𝕒𝕓𝕔𝕕𝕖𝕗𝕘𝕙𝕚𝕛𝕜𝕝𝕞𝕟𝕠𝕡𝕢𝕣𝕤𝕥𝕦𝕧𝕨𝕩𝕪𝕫',
                        '𝔸𝔹ℂ𝔻𝔼𝔽𝔾ℍ𝕀𝕁𝕂𝕃𝕄ℕ𝕆ℙℚℝ𝕊𝕋𝕌𝕍𝕎𝕏𝕐ℤ',
                        '𝟘𝟙𝟚𝟛𝟜𝟝𝟞𝟟𝟠𝟡'),
        "𝒮𝒸𝓇𝒾𝓅𝓉": ('𝒶𝒷𝒸𝒹ℯ𝒻ℊ𝒽𝒾𝒿𝓀𝓁𝓂𝓃ℴ𝓅𝓆𝓇𝓈𝓉𝓊𝓋𝓌𝓍𝓎𝓏',
                   '𝒜ℬ𝒞𝒟ℰℱ𝒢ℋℐ𝒥𝒦ℒℳ𝒩𝒪𝒫𝒬ℛ𝒮𝒯𝒰𝒱𝒲𝒳𝒴𝒵',
                   '𝟢𝟣𝟤𝟥𝟦𝟧𝟨𝟩𝟪𝟫'),
        "𝖥𝗋𝖺𝗄𝗍𝗎𝗋": ('𝖆𝖇𝖈𝖉𝖊𝖋𝖌𝖍𝖎𝖏𝖐𝖑𝖒𝖓𝖔𝖕𝖖𝖗𝖘𝖙𝖚𝖛𝖜𝖝𝖞𝖟',
                    '𝕬𝕭𝕮𝕯𝕰𝕱𝕲𝕳𝕴𝕵𝕶𝕷𝕸𝕹𝕺𝕻𝕼𝕽𝕾𝕿𝖀𝖁𝖂𝖃𝖄𝖅',
                    '𝟎𝟏𝟐𝟑𝟒𝟓𝟔𝟕𝟖𝟗'),
        "𝕊𝖺𝗇𝗌 𝕊𝖾𝗋𝗂𝖿": ('𝖺𝖻𝖼𝖽𝖾𝖿𝗀𝗁𝗂𝗃𝗄𝗅𝗆𝗇𝗈𝗉𝗊𝗋𝗌𝗍𝗎𝗏𝗐𝗑𝗒𝗓',
                      '𝖠𝖡𝖢𝖣𝖤𝖥𝖦𝖧𝖨𝖩𝖪𝖫𝖬𝖭𝖮𝖯𝖰𝖱𝖲𝖳𝖴𝖵𝖶𝖷𝖸𝖹',
                      '𝟢𝟣𝟤𝟥𝟦𝟧𝟨𝟩𝟪𝟫'),
        "𝕊𝖺𝗇𝗌 𝕊𝖾𝗋𝗂𝖿 𝖡𝗈𝗅𝖽": ('𝖺𝖻𝖼𝖽𝖾𝖿𝗀𝗁𝗂𝗃𝗄𝗅𝗆𝗇𝗈𝗉𝗊𝗋𝗌𝗍𝗎𝗏𝗐𝗑𝗒𝗓',
                          '𝖠𝖡𝖢𝖣𝖤𝖥𝖦𝖧𝖨𝖩𝖪𝖫𝖬𝖭𝖮𝖯𝖰𝖱𝖲𝖳𝖴𝖵𝖶𝖷𝖸𝖹',
                          '𝟬𝟭𝟮𝟯𝟰𝟱𝟲𝟳𝟴𝟵'),
        "𝒮𝒶𝓃𝓈 𝒮𝑒𝓇𝒾𝒻 𝐼𝓉𝒶𝓁𝒾𝒸": ('𝒶𝒷𝒸𝒹ℯ𝒻ℊ𝒽𝒾𝒿𝓀𝓁𝓂𝓃ℴ𝓅𝓆𝓇𝓈𝓉𝓊𝓋𝓌𝓍𝓎𝓏',
                            '𝒜ℬ𝒞𝒟ℰℱ𝒢ℋℐ𝒥𝒦ℒℳ𝒩𝒪𝒫𝒬ℛ𝒮𝒯𝒰𝒱𝒲𝒳𝒴𝒵',
                            '𝟢𝟣𝟤𝟥𝟦𝟧𝟨𝟩𝟪𝟫'),
        "𝚄𝚗𝚍𝚎𝚛𝚕𝚒𝚗𝚎": ('a̲b̲c̲d̲e̲f̲g̲h̲i̲j̲k̲l̲m̲n̲o̲p̲q̲r̲s̲t̲u̲v̲w̲x̲y̲z̲',
                    'A̲B̲C̲D̲E̲F̲G̲H̲I̲J̲K̲L̲M̲N̲O̲P̲Q̲R̲S̲T̲U̲V̲W̲X̲Y̲Z̲',
                    '0̲1̲2̲3̲4̲5̲6̲7̲8̲9̲'),
        "̶S̶t̶r̶o̶k̶e̶": ('a̶b̶c̶d̶e̶f̶g̶h̶i̶j̶k̶l̶m̶n̶o̶p̶q̶r̶s̶t̶u̶v̶w̶x̶y̶z̶',
                    'A̶B̶C̶D̶E̶F̶G̶H̶I̶J̶K̶L̶M̶N̶O̶P̶Q̶R̶S̶T̶U̶V̶W̶X̶Y̶Z̶',
                    '0̶1̶2̶3̶4̶5̶6̶7̶8̶9̶'),
        "🅲🅸🆁🅲🅻🅴🅳": ('ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ',
                  'ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ',
                  '⓪①②③④⑤⑥⑦⑧⑨'),
        "🅟🅐🅡🅔🅝🅣🅗🅔🅢🅘🅢": ('🅐🅑🅒🅓🅔🅕🅖🅗🅘🅙🅚🅛🅜🅝🅞🅟🅠🅡🅢🅣🅤🅥🅦🅧🅨🅩',
                     '🄰🄱🄲🄳🄴🄵🄶🄷🄸🄹🄺🄻🄼🄽🄾🄿🅀🅁🅂🅃🅄🅅🅆🅇🅈🅉',
                     '0123456789'),
        "ℂ𝕚𝕣𝕔𝕝𝕖𝕕 𝕊𝕢𝕦𝕒𝕣𝕖": ('🅰🅱🅲🅳🅴🅵🅶🅷🅸🅹🅺🅻🅼🅽🅾🅿🆀🆁🆂🆃🆄🆅🆆🆇🆈🆉',
                         '🄰🄱🄲🄳🄴🄵🄶🄷🄸🄹🄺🄻🄼🄽🄾🄿🅀🅁🅂🅃🅄🅅🅆🅇🅈🅉',
                         '0123456789'),
        "𝕊𝕞𝕒𝕝𝕝 ℂ𝕒𝕡𝕤": ('ᵃᵇᶜᵈᵉᶠᵍʰⁱʲᵏˡᵐⁿᵒᵖᵟʳˢᵗᵘᵛʷˣʸᶻ',
                      'ᴬᴮᶜᴰᴱᶠᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾᵠᴿˢᵀᵁⱽᵂˣʸᶻ',
                      '𝟢𝟣𝟤𝟥𝟦𝟧𝟨𝟩𝟪𝟫'),
    }

    result = []
    for style_name, (style_lower, style_upper, style_digits) in styles.items():
        transformed = []
        for ch in text:
            if 'a' <= ch <= 'z':
                idx = ord(ch) - ord('a')
                transformed.append(style_lower[idx])
            elif 'A' <= ch <= 'Z':
                idx = ord(ch) - ord('A')
                transformed.append(style_upper[idx])
            elif '0' <= ch <= '9':
                idx = ord(ch) - ord('0')
                transformed.append(style_digits[idx])
            elif ch in persian_list:
                transformed.append(ch)  
            else:
                transformed.append(ch)
        result.append({"style_name": style_name, "transformed_text": ''.join(transformed)})
    return result
    
def get_banner_exceptions_list(cursor):
    cursor.execute("SELECT group_guid FROM banner_exceptions")
    rows = cursor.fetchall()
    if not rows:
        return "📭 هیچ گروه استثنایی ثبت نشده است.", []
    text = "━━━━━━━━━━━━━━━━━━━━\n🚫 لیست گروه‌های استثنا (عدم دریافت بنر)\n━━━━━━━━━━━━━━━━━━━━\n"
    mono_parts = []
    for (guid,) in rows:
        group_name = guid
        result = _api_call("getChat", {"chat_id": guid})
        if result and result.get("status") == "OK":
            chat_data = result.get("data", {}).get("chat", {})
            group_name = chat_data.get("title") or guid
        text += f"👥 {group_name}\n{guid}\n━━━━━━━━━━━━━━━━━━━━\n"
        mono_parts.append({"text": guid})
    return text, mono_parts

def get_banner_exceptions(cursor):
    cursor.execute("SELECT group_guid FROM banner_exceptions")
    return [row[0] for row in cursor.fetchall()]
def delete_group_completely(cursor, group_guid):
    cursor.execute("DELETE FROM groups WHERE guid = %s", (group_guid,))
    cursor.execute("DELETE FROM allowed_groups WHERE group_guid = %s", (group_guid,))
    cursor.execute("DELETE FROM locks WHERE group_guid = %s", (group_guid,))
    cursor.execute("DELETE FROM group_settings WHERE group_guid = %s", (group_guid,))
    cursor.execute("DELETE FROM user_stats WHERE group_guid = %s", (group_guid,))
    cursor.execute("DELETE FROM message_log WHERE group_guid = %s", (group_guid,))
    cursor.execute("DELETE FROM mutes WHERE group_guid = %s", (group_guid,))
    cursor.execute("DELETE FROM bans WHERE group_guid = %s", (group_guid,))
    cursor.execute("DELETE FROM chatbot WHERE group_guid = %s", (group_guid,))

def remove_allowed_group(cursor, group_guid):
    cursor.execute("DELETE FROM allowed_groups WHERE group_guid=%s", (group_guid,))

def is_group_allowed(cursor, group_guid):
    cursor.execute("SELECT expires_at FROM allowed_groups WHERE group_guid=%s", (group_guid,))
    row = cursor.fetchone()
    if not row:
        return False
    expires_at = row[0]
    if expires_at < int(time.time()):
        cursor.execute("DELETE FROM allowed_groups WHERE group_guid=%s", (group_guid,))
        return False
    return True
    
def get_full_user_info_by_chat(chat_id):
    """دریافت نام کامل و یوزرنیم کاربر از طریق chat_id با متد getChat"""
    result = _api_call("getChat", {"chat_id": chat_id})
    if result and result.get("status") == "OK":
        data = result.get("data", {})
        chat = data.get("chat", {})
        first_name = chat.get("first_name", "")
        last_name = chat.get("last_name", "")
        username = chat.get("username", "")
        full_name = f"{first_name} {last_name}".strip()
        if not full_name:
            full_name = username or chat_id
        return full_name, username
    return chat_id, ""

def get_chat_title(chat_guid):
    """دریافت عنوان گروه/کانال از API"""
    result = _api_call("getChat", {"chat_id": chat_guid})
    if result and result.get("status") == "OK":
        chat_data = result.get("data", {}).get("chat", {})
        return chat_data.get("title") or chat_guid
    return chat_guid

def get_welcome_text(cursor, chat_id, user_guid, OWNER_ID):
    log_message(f"📥 get_welcome_text called: chat_id={chat_id}, user_guid={user_guid}, OWNER_ID={OWNER_ID}", "DEBUG")
    
    full_name, username = get_full_user_info_by_chat(chat_id)
    guid = user_guid

    try:
        cursor.execute("SELECT value FROM bot_state WHERE `key`='bot_mode'")
        row = cursor.fetchone()
        bot_mode = row[0] if row and row[0] else "normal"
        log_message(f"📊 حالت ربات دریافت شد: {bot_mode}", "DEBUG")
    except Exception as e:
        log_message(f"⚠️ خطا در دریافت bot_mode: {e}", "WARNING")
        bot_mode = "normal"  # پیش‌فرض

    if bot_mode == "subscription":
        mode_display = "اشتراکی"
    else:
        mode_display = "رایگان"  # یا "عادی" / "normal"

    user_role_text = ""
    
    if user_guid == OWNER_ID:
        user_role_text = "🔹 شما سازنده ربات هستید."
        log_message(f"✅ کاربر {user_guid} سازنده ربات است", "INFO")
    else:
        try:
            log_message(f"🔍 در حال اجرای کوئری برای کاربر {user_guid}", "DEBUG")
            
            cursor.execute("""
                SELECT guid, owner, admin1, admin2, admin3, active
                FROM groups 
                WHERE guid LIKE 'g0%%' 
                AND (owner = %s OR admin1 = %s OR admin2 = %s OR admin3 = %s)
            """, (user_guid, user_guid, user_guid, user_guid))
            
            rows = cursor.fetchall()
            
            log_message(f"🔍 تعداد گروه‌های یافت شده برای کاربر {user_guid}: {len(rows)}", "DEBUG")
            
            for idx, row in enumerate(rows):
                g_guid, owner, admin1, admin2, admin3, active = row
                log_message(f"📋 گروه #{idx+1}: guid={g_guid}, owner={owner}, admin1={admin1}, admin2={admin2}, admin3={admin3}, active={active}", "DEBUG")

            owner_count = 0
            admin_count = 0

            for g_guid, owner, admin1, admin2, admin3, active in rows:
                if user_guid == owner:
                    owner_count += 1
                    log_message(f"👑 کاربر {user_guid} در گروه {g_guid} نقش مالک دارد", "DEBUG")
                elif user_guid in (admin1, admin2, admin3):
                    admin_count += 1
                    log_message(f"👤 کاربر {user_guid} در گروه {g_guid} نقش ادمین دارد", "DEBUG")
                else:
                    log_message(f"⚠️ کاربر {user_guid} در گروه {g_guid} نقشی ندارد (با وجود اینکه کوئری برگردانده!)", "WARNING")

            log_message(f"📊 آمار نهایی: owner_count={owner_count}, admin_count={admin_count}", "DEBUG")

            if owner_count > 0 and admin_count > 0:
                user_role_text = f"🔹 شما در {owner_count} گروه مالک و در {admin_count} گروه ادمین هستید."
                log_message(f"✅ پیام: مالک {owner_count} گروه و ادمین {admin_count} گروه", "INFO")
            elif owner_count > 0:
                user_role_text = f"🔹 شما در {owner_count} گروه مالک هستید."
                log_message(f"✅ پیام: مالک {owner_count} گروه", "INFO")
            elif admin_count > 0:
                user_role_text = f"🔹 شما در {admin_count} گروه ادمین هستید."
                log_message(f"✅ پیام: ادمین {admin_count} گروه", "INFO")
            else:
                user_role_text = "🔹 شما مالک یا ادمین هیچ گروهی نیستید."
                log_message(f"ℹ️ پیام: کاربر هیچ نقشی در گروه‌ها ندارد", "INFO")
                
        except Exception as e:
            log_message(f"❌ خطا در get_welcome_text برای کاربر {user_guid}: {e}", "ERROR")
            import traceback
            log_message(traceback.format_exc(), "ERROR")
            user_role_text = "🔹 شما مالک یا ادمین هیچ گروهی نیستید."

    final_text = f"""━━━━━━━━━━━━━━━━━━
✨ به ربات خوش آمدید ✨
━━━━━━━━━━━━━━━━━━
👤 نام: {full_name}

{user_role_text}

حالت ربات: {mode_display}

#گوید_کاربر_فعال_کننده :/>
{guid}

📌 از دکمه‌های پایین صفحه استفاده کنید.
📖 برای راهنمای کامل /help را بفرستید.
━━━━━━━━━━━━━━━━━━"""
    
    log_message(f"📤 خروجی نهایی برای کاربر {user_guid}:\n{final_text}", "DEBUG")
    return final_text

def get_user_panel_text(cursor, chat_id, user_guid):
    full_name, username = get_full_user_info_by_chat(chat_id)
    guid = user_guid
    username_line = f"📛 یوزرنیم: @{username}" if username else ""
    return f"""━━━━━━━━━━━━━━━━━━━━
👤 پنل کاربری
━━━━━━━━━━━━━━━━━━━━
👤 نام: {full_name}
🆔 گوید: {guid}
{username_line}
━━━━━━━━━━━━━━━━━━━━
از دکمه‌های زیر استفاده کنید:"""
def get_helpp_text():
    return """━━━━━━━━━━━━━━━━━━━━
📖 راهنمای پنل
━━━━━━━━━━━━━━━━━━━━
♦1- پنل مدیریت

♦ لیست گروه‌ها: قابلیت مشاهده گروه‌ها گروه‌های فعال و غیر فعال

♦ آمار کلی: مشاهده کل گروه‌ها و گروه‌های فعال کاربرای فعال تعداد پیام کلی

♦ حذف گروه: این قابلیت برای غیر فعال کردن ربات در گروه‌ها است که با گوید گروه گوید گروه حذف می‌شود

♦ افزودن گروه: این قابلیت برای اضافه کردن گروه با گوید و تنظیم زمان فعال می‌شود

♦ پیام همگانی این قابلیت برای ارسال به کل پیوی های ربات است

♦ حالت ربات: برای اشتراکی کردن یا فعال سازی دائم ربات

♦2 پنل تبلیغات

♦ لیست استثنا:  قابلیت نمایش روه‌های که لینک تبلیغ رسال نمی‌شود

♦ ثبت بنر: روی دکمه ثبت بنر کلیک کنید و یک بنر فوروارد کنید 
تا بنر ثبت شود

♦ متوقف بنر: برای حذف کردن بنر

♦ مدیریت استثنا: این قابلیت برای اضافه کردن گروه و حذف کردن گروه
━━━━━━━━━━━━━━━━━━━━"""

def get_help_text(cursor, owner_name=None):
    try:
        cursor.execute("SELECT value FROM bot_state WHERE `key`='bot_mode'")
        row = cursor.fetchone()
        bot_mode = row[0] if row else "normal"
    except Exception:
        bot_mode = "normal"

    if bot_mode != "subscription":
        return """━━━━━━━━━━━━━━━━━━
🤖 ربات در حالت رایگان است.
━━━━━━━━━━━━━━━━━━"""
    else:
        # اگر owner_name داده نشده، از مقدار پیش‌فرض استفاده کن
        if owner_name is None:
            owner_name = "@ReZa_TOK"  # مقدار قبلی
        
        return f"""━━━━━━━━━━━━━━━━━━
💸 قیمت اشتراک 
━━━━━━━━━━━━━━━━━━
♦ خرید اشتراک ربات ماه ۱۵ هزار تومان می‌باشد
♦ مثل: که برای دو ماه ۳۰ هزار تومان می‌باشد
♦ برای خرید: کلیک کن👇
[ -𖣐->      @{owner_name} ] 
━━━━━━━━━━━━━━━━━━"""

def get_bot_stats(cursor):
    cursor.execute("SELECT COUNT(*) FROM groups WHERE guid LIKE 'g0%'")
    total_groups = cursor.fetchone()[0] or 0
    
    cursor.execute("SELECT COUNT(*) FROM groups WHERE guid LIKE 'g0%' AND active=1")
    active_groups = cursor.fetchone()[0] or 0
    
    cursor.execute("SELECT COUNT(DISTINCT user_guid) FROM user_stats")
    total_users = cursor.fetchone()[0] or 0
    
    cursor.execute("SELECT SUM(messages_count) FROM user_stats")
    total_messages = cursor.fetchone()[0] or 0
    
    return f"""━━━━━━━━━━━━━━━━━━━━
📊 آمار کلی ربات
━━━━━━━━━━━━━━━━━━━━
👥 کل گروه‌ها: {total_groups}
✅ گروه‌های فعال: {active_groups}
👤 کل کاربران: {total_users}
💬 کل پیام‌ها: {total_messages}
━━━━━━━━━━━━━━━━━━━━"""

def get_user_stats(cursor, user_guid, group_guid, user_name):
    import time
    import jdatetime

    if not group_guid.startswith('b0'):
        log_message("[ERROR] get_user_stats called in non-PV mode", "ERROR")
        return "❌ این دستور فقط در پیوی قابل استفاده است.", []

    bot_mode = "normal"
    try:
        cursor.execute("SELECT value FROM bot_state WHERE `key`='bot_mode'")
        row = cursor.fetchone()
        if row:
            bot_mode = row[0]
    except:
        pass

    # دریافت نام کاربر از API (در صورت امکان)
    try:
        result = _api_call("getChat", {"chat_id": group_guid})
        if result and result.get("status") == "OK":
            chat_data = result.get("data", {}).get("chat", {})
            first_name = chat_data.get("first_name", "")
            last_name = chat_data.get("last_name", "")
            username = chat_data.get("username", "")
            fetched_name = f"{first_name} {last_name}".strip()
            if fetched_name:
                user_name = fetched_name
            elif username:
                user_name = username
            else:
                user_name = user_guid
    except:
        pass

    # آمار کلی کاربر
    cursor.execute("""
        SELECT 
            COALESCE(SUM(messages_count), 0) as total_messages,
            COALESCE(SUM(today_messages), 0) as total_today,
            COALESCE(SUM(warnings), 0) as total_warnings
        FROM user_stats WHERE user_guid=%s
    """, (user_guid,))
    row = cursor.fetchone()
    total_messages = row[0] if row else 0
    total_today = row[1] if row else 0
    total_warnings = row[2] if row else 0

    # فقط گروه‌هایی که کاربر مالک آن‌هاست
    cursor.execute("""
        SELECT guid, owner, admin1, admin2, admin3, active
        FROM groups 
        WHERE owner=%s
    """, (user_guid,))
    managed_groups = cursor.fetchall()

    # تعیین سطح کلی کاربر (فقط بر اساس مالکیت)
    overall_level = "مالک گروه" if managed_groups else "کاربر عادی"

    # ساخت لیست گروه‌ها
    groups_list = ""
    if managed_groups:
        groups_list = "━━━━━━━━━━━━━━━━━━\n📅 وضعیت گروه‌ها:\n━━━━━━━━━━━━━━━━━━"
        for g_guid, owner, admin1, admin2, admin3, active in managed_groups:
            group_name = g_guid
            try:
                result = _api_call("getChat", {"chat_id": g_guid})
                if result and result.get("status") == "OK":
                    chat_data = result.get("data", {}).get("chat", {})
                    group_name = chat_data.get("title") or g_guid
            except:
                pass

            active_status = "✅ فعال" if active == 1 else "❌ غیرفعال"
            group_lines = f"\n👥 نام گروه: {group_name}\n🔰 وضعیت: {active_status}"

            if bot_mode == "subscription":
                cursor.execute("SELECT expires_at FROM allowed_groups WHERE group_guid=%s", (g_guid,))
                exp_row = cursor.fetchone()
                if exp_row and exp_row[0]:
                    expires_at = exp_row[0]
                    now = int(time.time())
                    if expires_at > now:
                        remaining = expires_at - now
                        days = remaining // 86400
                        hours = (remaining % 86400) // 3600
                        expiry_str = f"{days} روز و {hours} ساعت" if days > 0 else f"{hours} ساعت"
                        try:
                            gregorian_date = datetime.fromtimestamp(expires_at)
                            shamsi_date = jdatetime.date.fromgregorian(date=gregorian_date)
                            expiry_date = shamsi_date.strftime("%Y/%m/%d")
                        except:
                            expiry_date = "نامشخص"
                        sub_status = "✅ فعال"
                        remaining_text = f"⏳ باقی‌مانده: {expiry_str}"
                    else:
                        sub_status = "❌ منقضی شده"
                        remaining_text = "⏳ باقی‌مانده: ۰ روز"
                        expiry_date = "منقضی شده"
                else:
                    sub_status = "❌ ثبت نشده"
                    remaining_text = "⏳ باقی‌مانده: ثبت نشده"
                    expiry_date = "ثبت نشده"

                group_lines += f"\n💰 اشتراک: {sub_status}\n📅 انقضا: {expiry_date}\n{remaining_text}"

            groups_list += group_lines
    else:
        groups_list = "🔹 شما در هیچ گروهی مالک نیستید."

    # ساخت متن نهایی
    text = f"""━━━━━━━━━━━━━━━━━━
📊 وضعیت آمار کلی شما
━━━━━━━━━━━━━━━━━━
👤 کاربر: {user_name}
#گوید_کاربر_فعال_کننده:/> {user_guid}

📈 آمار کلی:
⚡ سطح کلی: {overall_level}
⚠️ کل اخطارها: {total_warnings}
💬 پیام امروز: {total_today}
💬 کل پیام‌ها: {total_messages}
{groups_list}
━━━━━━━━━━━━━━━━━━"""
    mono_parts = [{"text": user_guid}]
    return text, mono_parts

def update_user_message_count(cursor, user_guid, group_guid):
    today = datetime.now().strftime("%Y-%m-%d")
    cursor.execute("SELECT today_messages, last_date FROM user_stats WHERE user_guid=%s AND group_guid=%s", 
                   (user_guid, group_guid))
    row = cursor.fetchone()
    if row:
        last_date = row[1]
        if last_date is None or last_date != today:
            cursor.execute("""
                UPDATE user_stats SET messages_count = messages_count + 1,
                                      today_messages = 1,
                                      last_date = %s
                WHERE user_guid=%s AND group_guid=%s
            """, (today, user_guid, group_guid))
        else:
            cursor.execute("""
                UPDATE user_stats SET messages_count = messages_count + 1,
                                      today_messages = today_messages + 1
                WHERE user_guid=%s AND group_guid=%s
            """, (user_guid, group_guid))
    else:
        cursor.execute("""
            INSERT INTO user_stats (user_guid, group_guid, messages_count, today_messages, join_date, last_date)
            VALUES (%s, %s, 1, 1, %s, %s)
        """, (user_guid, group_guid, today, today))

def add_warning(cursor, user_guid, group_guid, warning_limit):
    cursor.execute("""
        INSERT INTO user_stats (user_guid, group_guid, warnings, messages_count, today_messages, join_date, last_date)
        VALUES (%s, %s, 1, 0, 0, %s, %s)
        ON DUPLICATE KEY UPDATE warnings = warnings + 1
    """, (user_guid, group_guid, datetime.now().strftime("%Y-%m-%d"), datetime.now().strftime("%Y-%m-%d")))
    
    cursor.execute("SELECT warnings FROM user_stats WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))
    result = cursor.fetchone()
    return result and result[0] > warning_limit

def remove_warning(cursor, user_guid, group_guid):
    cursor.execute("""
        UPDATE user_stats SET warnings = warnings - 1 
        WHERE user_guid=%s AND group_guid=%s AND warnings > 0
    """, (user_guid, group_guid))

def add_mute(cursor, user_guid, group_guid, duration_seconds):
    until_time = int(time.time()) + duration_seconds
    cursor.execute("REPLACE INTO mutes (user_guid, group_guid, until_time) VALUES (%s, %s, %s)",
                   (user_guid, group_guid, until_time))

def remove_mute(cursor, user_guid, group_guid):
    cursor.execute("DELETE FROM mutes WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))

def is_muted(cursor, user_guid, group_guid):
    cursor.execute("SELECT until_time FROM mutes WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))
    result = cursor.fetchone()
    if result:
        if result[0] > int(time.time()):
            return True
        else:
            remove_mute(cursor, user_guid, group_guid)
    return False

def get_banned_users(cursor, group_guid):
    cursor.execute("SELECT user_guid, banned_at FROM bans WHERE group_guid=%s ORDER BY banned_at DESC", (group_guid,))
    return cursor.fetchall()

def is_banned(cursor, user_guid, group_guid):
    cursor.execute("SELECT 1 FROM bans WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))
    return cursor.fetchone() is not None

def get_lock_status(cursor, group_guid, lock_type):
    try:
        cursor.execute(f"SELECT {lock_type} FROM locks WHERE group_guid=%s", (group_guid,))
        result = cursor.fetchone()
        return result[0] if result else 0
    except Exception:
        return 0


    
def set_lock(cursor, group_guid, lock_type, value):
    cursor.execute(f"""
        INSERT INTO locks (group_guid, {lock_type})
        VALUES (%s, %s)
        ON DUPLICATE KEY UPDATE {lock_type} = VALUES({lock_type})
    """, (group_guid, value))

def add_medal(cursor, user_guid, group_guid, medal_type=None):
    # بررسی وجود رکورد برای کاربر در این گروه
    cursor.execute("SELECT medal_score FROM user_stats WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))
    row = cursor.fetchone()
    if row:
        # اگر رکورد وجود دارد، medal_score را یک واحد افزایش بده
        cursor.execute("UPDATE user_stats SET medal_score = medal_score + 1 WHERE user_guid=%s AND group_guid=%s",
                       (user_guid, group_guid))
    else:
        # اگر رکورد وجود ندارد، یک رکورد جدید با medal_score=1 ایجاد کن
        from datetime import datetime
        today = datetime.now().strftime("%Y-%m-%d")
        cursor.execute("""
            INSERT INTO user_stats (user_guid, group_guid, medal_score, messages_count, today_messages, warnings, join_date, last_date)
            VALUES (%s, %s, 1, 0, 0, 0, %s, %s)
        """, (user_guid, group_guid, today, today))

def remove_medal(cursor, user_guid, group_guid, medal_type):
    cursor.execute("DELETE FROM medals WHERE user_guid=%s AND group_guid=%s AND medal_type=%s", 
                   (user_guid, group_guid, medal_type))

def get_user_medals(cursor, user_guid, group_guid):
    cursor.execute("SELECT medal_type FROM medals WHERE user_guid=%s AND group_guid=%s", 
                   (user_guid, group_guid))
    return [row[0] for row in cursor.fetchall()]

def ban_chat_member(chat_id, user_id):
    payload = {"chat_id": chat_id, "user_id": user_id}
    return _api_call("banChatMember", payload)

def unban_chat_member(chat_id, user_id):
    payload = {"chat_id": chat_id, "user_id": user_id}
    return _api_call("unbanChatMember", payload)

def clear_user_data(c, user_guid, group_guid):
    try:
        c.execute("DELETE FROM mutes WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))
        c.execute("DELETE FROM medals WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))
        c.execute("UPDATE groups SET owner = NULL WHERE owner = %s AND guid = %s", (user_guid, group_guid))
        for admin_field in ['admin1', 'admin2', 'admin3']:
            c.execute(f"UPDATE groups SET {admin_field} = NULL WHERE {admin_field} = %s AND guid = %s", (user_guid, group_guid))
        c.execute("DELETE FROM user_stats WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))
        c.execute("DELETE FROM bans WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))
        print(f"✅ تمام اطلاعات کاربر {user_guid} در گروه {group_guid} پاک شد")
        return True
    except Exception as e:
        print(f"❌ خطا در پاک کردن اطلاعات کاربر: {e}")
        return False

def add_ban(c, user_guid, group_guid):
    try:
        result = ban_chat_member(group_guid, user_guid)
        if result and result.get("status") == "OK":
            print(f"✅ کاربر {user_guid} با موفقیت از گروه {group_guid} بن شد")
            clear_user_data(c, user_guid, group_guid)
            ban_time = int(time.time())
            c.execute("REPLACE INTO bans (user_guid, group_guid, banned_at) VALUES (%s, %s, %s)",
                     (user_guid, group_guid, ban_time))
            return True
        else:
            error_msg = result.get("data", {}).get("error", {}).get("message", "دسترسی کافی وجود ندارد") if result else "خطای نامشخص"
            print(f"❌ خطا در بن کردن کاربر: {error_msg}")
            return False
    except Exception as e:
        print(f"❌ خطا در add_ban: {e}")
        return False

def remove_ban(c, user_guid, group_guid):
    try:
        result = unban_chat_member(group_guid, user_guid)
        if result and result.get("status") == "OK":
            print(f"✅ بن کاربر {user_guid} در گروه {group_guid} رفع شد")
            c.execute("DELETE FROM bans WHERE user_guid=%s AND group_guid=%s", 
                     (user_guid, group_guid))
            return True
        else:
            error_msg = result.get("data", {}).get("error", {}).get("message", "دسترسی کافی وجود ندارد") if result else "خطای نامشخص"
            print(f"❌ خطا در رفع بن: {error_msg}")
            return False
    except Exception as e:
        print(f"❌ خطا در remove_ban: {e}")
        return False

def get_list_qofli(cursor, group_guid):
    cursor.execute("INSERT IGNORE INTO locks (group_guid) VALUES (%s)", (group_guid,))
    locks = [
        ('لینک          ', 'link'), ('فوروارد     ', 'forward'), ('ویرایش     ', 'edit'),
        ('عکس       ', 'photo'), ('فیلم         ', 'video'), ('فایل         ', 'file'),
        ('زیپ          ', 'zip'), ('عدد         ', 'number'), ('آهنگ        ', 'music'),
        ('ویس       ', 'voice'), ('آیدی        ', 'mention'), ('کد هنگی ', 'repetition'),
        ('استیکر     ', 'sticker'), ('هشتگ     ', 'hashtag'), ('کد           ', 'code'),
        ('فحاشی    ', 'swear'), ('نظرسنجی ', 'poll'), ('استوری    ', 'story'),
        ('لوکیشن    ', 'location'), ('پخش زنده', 'live')
    ]
    width = 1
    text = """━━━━━━━━━━━━━━━
(❌) -♡- >{ لیست قفلی } <¥> 
━━━━━━━━━━━━━━━"""
    for i, (name, col) in enumerate(locks, 1):
        status = get_lock_status(cursor, group_guid, col)
        is_locked = (status & ENABLED_FLAG) != 0
        lock_icon = "🔒" if is_locked else "🔓"
        if is_locked:
            ban_icon = "🚫" if (status & 1) else "➕"
            warn_icon = "⚠️" if (status & 2) else "➕"
            mute_icon = "🔇" if (status & 4) else "➕"
        else:
            ban_icon = warn_icon = mute_icon = "➕"
        text += f"\n❌>{i:1}>{name:<{width}}{lock_icon}>{warn_icon}>{ban_icon}>{mute_icon}"
    text += """
━━━━━━━━━━━━━━━
🔓 > 1 باز    🔒 > 1 قفل
🚫 > بن 1 فعال/غیرفعال 
⚠️ > اخطار 1 فعال/غیرفعال 
🔇 > سکوت 1 فعال/غیرفعال 
♦> همه باز / همه قفل
━━━━━━━━━━━━━━━"""
    cursor.execute("SELECT default_warning_limit, default_mute_time FROM group_settings WHERE group_guid=%s", (group_guid,))
    row = cursor.fetchone()
    if row:
        warning_limit = row[0] if row[0] is not None else 3
        mute_time = row[1] if row[1] is not None else 3600
        if mute_time >= 3600:
            mute_display = f"{mute_time // 3600} ساعت"
        elif mute_time >= 60:
            mute_display = f"{mute_time // 60} دقیقه"
        else:
            mute_display = f"{mute_time} ثانیه"
    else:
        warning_limit = 3
        mute_display = "1 ساعت"
    text += f"""
⚠️ > اخطار تنظیم شده: {warning_limit}
🔇 > سکوت تنظیم شده: {mute_display}
━━━━━━━━━━━━━━━"""
    return text
def set_user_medal(cursor, user_guid, group_guid, score):
    log_message(f"🔄 set_user_medal called: user={user_guid}, group={group_guid}, score={score}", "DEBUG")
    try:
        if score is None:
            cursor.execute("""
                UPDATE user_stats 
                SET medal_score = NULL 
                WHERE user_guid=%s AND group_guid=%s
            """, (user_guid, group_guid))
            log_message(f"🗑️ Medal removed for user {user_guid} in group {group_guid}", "INFO")
        else:
            cursor.execute("""
                INSERT INTO user_stats (user_guid, group_guid, medal_score, messages_count, today_messages, warnings, join_date, last_date)
                VALUES (%s, %s, %s, 0, 0, 0, %s, %s)
                ON DUPLICATE KEY UPDATE medal_score = %s
            """, (user_guid, group_guid, score, datetime.now().strftime("%Y-%m-%d"), datetime.now().strftime("%Y-%m-%d"), score))
            log_message(f"⭐ Medal set to {score} for user {user_guid} in group {group_guid}", "INFO")
        cursor.connection.commit()
        return True
    except Exception as e:
        log_message(f"❌ Error in set_user_medal: {e}", "ERROR")
        return False
    
def set_user_asl(cursor, user_guid, group_guid, asl):
    """
    تنظیم اصل (ASL) برای کاربر در یک گروه خاص
    """
    try:
        cursor.execute("""
            INSERT INTO user_stats (user_guid, group_guid, asl)
            VALUES (%s, %s, %s)
            ON DUPLICATE KEY UPDATE asl = VALUES(asl)
        """, (user_guid, group_guid, asl))
        return True
    except Exception as e:
        print(f"Error in set_user_asl: {e}")
        return False

def set_user_lagab(cursor, user_guid, group_guid, lagab):
    """
    تنظیم لقب (Lagab) برای کاربر در یک گروه خاص
    """
    try:
        cursor.execute("""
            INSERT INTO user_stats (user_guid, group_guid, lagab)
            VALUES (%s, %s, %s)
            ON DUPLICATE KEY UPDATE lagab = VALUES(lagab)
        """, (user_guid, group_guid, lagab))
        return True
    except Exception as e:
        print(f"Error in set_user_lagab: {e}")
        return False
        
def get_user_amar(cursor, user_guid, group_guid, user_name, user_rank=0, is_self=True):
    try:
        rank_map = {0: "عادی", 1: "ادمین", 2: "مالک گروه", 3: "سازنده"}
        rank_text = rank_map.get(user_rank, "عادی")
        cursor.execute("SELECT default_warning_limit FROM group_settings WHERE group_guid=%s", (group_guid,))
        row_limit = cursor.fetchone()
        warning_limit = row_limit[0] if row_limit and row_limit[0] is not None else 3
        cursor.execute("""
            SELECT COALESCE(messages_count, 0),
                   COALESCE(today_messages, 0),
                   COALESCE(warnings, 0),
                   COALESCE(level, 0),
                   join_date,
                   asl,
                   lagab,
                   medal_score
            FROM user_stats WHERE user_guid=%s AND group_guid=%s
        """, (user_guid, group_guid))
        row = cursor.fetchone()
        if row:
            messages, today, warnings, level, join_date, asl, lagab, medal_score = row
        else:
            messages = today = warnings = level = 0
            join_date = asl = lagab = medal_score = None
        warning_display = f"{warnings}/{warning_limit}"
        medal_display = str(medal_score) if medal_score and medal_score > 0 else "ندارد"
        ZWSP = "\u200B"
        if not user_name or user_name == "مشاهده":
            user_name = "مشاهده" + (ZWSP * (user_rank + 1))
        if join_date:
            try:
                date_obj = datetime.strptime(join_date, "%Y-%m-%d")
                import jdatetime
                join_display = jdatetime.date.fromgregorian(date=date_obj).strftime("%Y/%m/%d")
            except:
                join_display = join_date
        else:
            join_display = "ندارد"
        asl_display = asl if asl else "تنظیم نشده"
        lagab_display = lagab if lagab else "تنظیم نشده"
        rlm = "\u200F"
        guid_line = f"{rlm}🆔:/--♡->{user_guid}"
        title = "آمار شما" if is_self else "آمار کاربر"
        return f"""━━━━━━━━━━━━━━━
(📊) -♡- >{{ {title} }} <¥>
━━━━━━━━━━━━━━━
👤 اکانت کاربر: {user_name}
⚡ سطح: {rank_text}
🌍 اصل: {asl_display}
🏷 لقب: {lagab_display}
⚠️ اخطار: {warning_display}
💬 پیام امروز: {today}
💬 کل پیام‌ها: {messages}
🏅 مدال: {medal_display}
📅 تاریخ عضویت: {join_display}
╮━━━━ گوید اکانت ━━━━╭ 
{guid_line}
━━━━━━━━━━━━━━━"""
    except Exception as e:
        print(f"Error in get_user_amar: {e}")
        rlm = "\u200F"
        guid_line = f"{rlm}-♡-> {user_guid}"
        title = "آمار شما" if is_self else "آمار کاربر"
        return f"""━━━━━━━━━━━━━━━
(📊) -♡- >{{ {title} }} <¥>
━━━━━━━━━━━━━━━
👤 اکانت کاربر: {user_name}
⚡ سطح: نامشخص
🌍 اصل: تنظیم نشده
🏷 لقب: تنظیم نشده
⚠️ اخطار: 0/%s
💬 پیام امروز: 0
💬 کل پیام‌ها: 0
🏅 مدال: ندارد
📅 تاریخ عضویت: نامشخص
╮━━━━ گوید اکانت ━━━━╭ 
{guid_line}
━━━━━━━━━━━━━━━"""

def get_start_keypad(user_guid, cursor):
    if user_guid == OWNER_ID:
        return {
            "rows": [
                {"buttons": [{"id": "start_panel", "type": "Simple", "button_text": "⚙️ پنل مدیریت"}]},
                {"buttons": [{"id": "tabl_pan", "type": "Simple", "button_text": "⚙️ پنل تبلیغات"}]},
                {"buttons": [{"id": "start_helpo", "type": "Simple", "button_text": "⚙️ راهنما"}]}
            ],
            "resize_keyboard": True,
            "one_time_keyboard": False
        }

    bot_mode = "normal"
    try:
        cursor.execute("SELECT value FROM bot_state WHERE `key`='bot_mode'")
        row = cursor.fetchone()
        if row:
            bot_mode = row[0]
        log_message(f"[DEBUG] get_start_keypad: bot_mode = {bot_mode} for user {user_guid}", "DEBUG")
    except Exception as e:
        log_message(f"[ERROR] get_start_keypad: error reading bot_mode: {e}", "ERROR")

    if bot_mode == "subscription":
        stats_button_text = "𖣐 آمارم و مدت اشتراک 𖣐"
        third_row_buttons = [
            {"id": "user_groups", "type": "Simple", "button_text": "𖣐 گروه ها 𖣐"},
            {"id": "user_price", "type": "Simple", "button_text": "𖣐 قیمت اشتراک 𖣐"}
        ]
    else:
        stats_button_text = "𖣐 آمارم و گروه‌های من 𖣐"
        third_row_buttons = [
            {"id": "user_groups", "type": "Simple", "button_text": "𖣐 گروه ها 𖣐"}
        ]

    log_message(f"[DEBUG] stats_button_text = {stats_button_text}", "DEBUG")

    rows = [
        {"buttons": [{"id": "user_stats", "type": "Simple", "button_text": stats_button_text}]},
        {"buttons": [{"id": "user_active_groups", "type": "Simple", "button_text": "𖣐 آمار گروه‌های فعال 𖣐"}]},
        {"buttons": third_row_buttons},
        {"buttons": [{"id": "user_contact", "type": "Simple", "button_text": "𖣐 پشتیبانی 𖣐"}]}
    ]

    return {
        "rows": rows,
        "resize_keyboard": True,
        "one_time_keyboard": False
    }
    
def get_owner_panel_keypad():
    return {
        "rows": [
            {"buttons": [{"id": "owner_stats", "type": "Simple", "button_text": "📊 آمار کلی"}, {"id": "owner_groups", "type": "Simple", "button_text": "📋 لیست گروه‌ها"}]},
            {"buttons": [{"id": "owner_add_group", "type": "Simple", "button_text": "➕ افزودن گروه"}, {"id": "owner_remove_group", "type": "Simple", "button_text": "➖ حذف گروه"}]},
            {"buttons": [{"id": "owner_toggle_mode", "type": "Simple", "button_text": "🔄 حالت ربات"}, {"id": "owner_broadcast", "type": "Simple", "button_text": "📢 ارسال همگانی"}]},
            {"buttons": [{"id": "owner_back", "type": "Simple", "button_text": "🔙 بازگشت"}]}
        ],
        "resize_keyboard": True,
        "one_time_keyboard": False
    }
def get_owner_panelt_keypad():
    return {
        "rows": [
            {"buttons": [{"id": "owner_banner", "type": "Simple", "button_text": "📣 ثبت بنر"}, {"id": "owner_exception_list", "type": "Simple", "button_text": "📋 لیست استثنا"}]},
            {"buttons": [{"id": "owner_exception", "type": "Simple", "button_text": "🚫 مدیریت استثنا"}, {"id": "owner_stop_banner", "type": "Simple", "button_text": "⏹ توقف بنر"}]},
            {"buttons": [{"id": "owner_back", "type": "Simple", "button_text": "🔙 بازگشت"}]}
        ],
        "resize_keyboard": True,
        "one_time_keyboard": False
    }


_api_call_func = None

def is_entertainment_enabled(cursor, group_guid):
    try:
        cursor.execute("SELECT entertainment FROM group_settings WHERE group_guid=%s", (group_guid,))
        row = cursor.fetchone()
        return row and row[0] == 1
    except:
        return True  
def set_api_call_func(func):
    global _api_call_func
    _api_call_func = func

def _api_call(method, data=None):
    if _api_call_func is None:
        raise Exception("api_call function not set! Call set_api_call_func first")
    return _api_call_func(method, data)


    
def get_total_active_groups_count(cursor, user_guid=None):
    cursor.execute("SELECT COUNT(*) FROM groups ")
    count = cursor.fetchone()[0]
    
    text = f"""━━━━━━━━━━━━━━━━━━
   #ربات_در :/>[ {count} ] گروه فعال است
━━━━━━━━━━━━━━━━━━"""
    return text
    
    
def get_user_manag_groups(cursor, user_guid):
    return """━━━━━━━━━━━━━━━━━━
💯لینکدونی_لجندر->
[http://rubika.ir/LinkDoni_LeGaNdR]
👨‍🏫 آموزش_فعال_سازی_ربات -->
[ @AmUzeEsh_LeGaNdR ]
🏴‍☠️ربات مدیریت گروه --> 
[ http://rubika.ir/RiokoBot ]
━━━━━━━━━━━━━━━━━━"""
def set_chat_keypad(chat_id, keypad):
    payload = {"chat_id": chat_id, "chat_keypad_type": "New", "chat_keypad": keypad}
    return _api_call("editChatKeypad", payload)

def remove_chat_keypad(chat_id):
    payload = {"chat_id": chat_id, "chat_keypad_type": "Remove"}
    return _api_call("editChatKeypad", payload)

def get_group_amar(cursor, group_guid, group_name, member_count=None):
    try:
        cursor.execute("SELECT COUNT(DISTINCT user_guid) FROM user_stats WHERE group_guid=%s", (group_guid,))
        total_members = cursor.fetchone()[0] or 0
        if member_count is not None:
            total_members = member_count
        
        cursor.execute("SELECT SUM(messages_count) FROM user_stats WHERE group_guid=%s", (group_guid,))
        total_messages = cursor.fetchone()[0] or 0
        
        today = datetime.now().strftime("%Y-%m-%d")
        cursor.execute("SELECT SUM(today_messages) FROM user_stats WHERE group_guid=%s AND last_date=%s", 
                       (group_guid, today))
        today_messages = cursor.fetchone()[0] or 0
        
        current_time = int(time.time())
        cursor.execute("SELECT COUNT(*) FROM mutes WHERE group_guid=%s AND until_time > %s", (group_guid, current_time))
        muted_count = cursor.fetchone()[0] or 0
        
        cursor.execute("SELECT COUNT(*) FROM bans WHERE group_guid=%s", (group_guid,))
        banned_count = cursor.fetchone()[0] or 0
        
        cursor.execute("SELECT SUM(warnings) FROM user_stats WHERE group_guid=%s", (group_guid,))
        total_warnings = cursor.fetchone()[0] or 0
        
        cursor.execute("SELECT owner, admin1, admin2, admin3 FROM groups WHERE guid=%s", (group_guid,))
        row = cursor.fetchone()
        admin_count = 0
        if row:
            if row[0]: admin_count += 1 
            if row[1]: admin_count += 1   
            if row[2]: admin_count += 1   
            if row[3]: admin_count += 1   
        
        cursor.execute("SELECT group_status FROM group_settings WHERE group_guid=%s", (group_guid,))
        group_status_row = cursor.fetchone()
        group_status = "باز" if (group_status_row and group_status_row[0] == 1) else "بسته"
        
        cursor.execute("SELECT chatbot FROM group_settings WHERE group_guid=%s", (group_guid,))
        chatbot_row = cursor.fetchone()
        chatbot_status = "روشن" if (chatbot_row and chatbot_row[0] == 1) else "خاموش"

        cursor.execute("SELECT entertainment FROM group_settings WHERE group_guid=%s", (group_guid,))
        ent_row = cursor.fetchone()
        entertainment_status = "روشن" if (ent_row and ent_row[0] == 1) else "خاموش"

        cursor.execute("SELECT value FROM bot_state WHERE `key`='bot_mode'")
        mode_row = cursor.fetchone()
        subscription_mode = (mode_row and mode_row[0] == "subscription")
        subscription_status = "فعال" if subscription_mode else "غیرفعال"
        expires_at = None
        cursor.execute("SELECT expires_at FROM allowed_groups WHERE group_guid=%s", (group_guid,))
        exp_row = cursor.fetchone()
        if exp_row:
            expires_at = exp_row[0]

        if expires_at and expires_at > int(time.time()):
            remaining_seconds = expires_at - int(time.time())
            days = remaining_seconds // 86400
            hours = (remaining_seconds % 86400) // 3600
            if days > 0:
                remaining_str = f"{days} روز و {hours} ساعت"
            else:
                remaining_str = f"{hours} ساعت"
            expiry_datetime = datetime.fromtimestamp(expires_at)
            expiry_shamsi = jdatetime.date.fromgregorian(date=expiry_datetime).strftime("%Y/%m/%d")
            expiry_time = expiry_datetime.strftime(" %H:%M")
            expiry_date_str = f"{expiry_shamsi}{expiry_time}"
        else:
            expiry_date_str = "نامشخص"
            remaining_str = "نامشخص"
        
        return f"""━━━━━━━━━━━━━━━
(📊) -♡- >{{ آمار گروه }} <¥> 
━━━━━━━━━━━━━━━
🔱اسم گروه: {group_name}
🔱عضوهای فعال: {total_members}
💬 پیام‌ها: {total_messages}
💬 پیام‌های امروز: {today_messages}
⚠️ تعداد اخطار : {total_warnings}
🔇 سکوت ها: {muted_count}
🚫 بن شده: {banned_count}
⚖ تعداد مالک ادمین: {admin_count}
💰 وضعیت اشتراک: {subscription_status}
📅 انقضا: {expiry_date_str}
⏳ باقی‌مانده: {remaining_str}
━━━━━━━━━━━━━━━
♦برای حذف پیام
🔺دستور: حذف همه 
🔺دستور: حذف(عدد) 
🔺دستور: حذف (ریپلای)
━━━━━━━━━━━━━━━
🎤 سخنگو: {chatbot_status}
🎮 سرگرمی: {entertainment_status}
━━━━━━━━━━━━━━━
🔺گروه: {group_status}
━━━━━━━━━━━━━━━"""
    except Exception as e:
        print(f"Error in get_group_amar: {e}")
        return f"""━━━━━━━━━━━━━━━
(📊) -♡- >{{ آمار گروه }} <¥> 
━━━━━━━━━━━━━━━
🔱اسم گروه: {group_name}
🔱عضوهای فعال: 0
💬 پیام‌ها: 0
💬 پیام‌های امروز: 0
🚩 پیام حذف شده: 0
⚠️ تعداد اخطار : 0
🔇 سکوت ها: 0
🚫 بن شده: 0
⚖ تعداد مالک ادمین: 0
💰 وضعیت اشتراک: نامشخص
📅 انقضا: نامشخص
⏳ باقی‌مانده: نامشخص
━━━━━━━━━━━━━━━
♦ حذف پیام ها
♦ حذف پیام (عدد) 
♦ حذف (ریبلای) 
━━━━━━━━━━━━━━━
🎤 سخنگو: خاموش
🎮 سرگرمی: خاموش
━━━━━━━━━━━━━━━
🔺گروه: باز
━━━━━━━━━━━━━━━"""
def get_sereshgari_list():
    return """━━━━━━━━━━━━━━━
(📋) -♡- >{ لیست سرگرمی } <¥> 
━━━━━━━━━━━━━━━
1-چالش  2-تکست 3-خاطره 4-بیو
5-چیستان 6-داستان 7-دعا 8-فکت
9-فال 10-حدیث
5. جراعت - یک کاری
6. حقیقت - یک سوال 
━━━━━━━━━━━━━━━
🎲 بازی و شانس
تاس - انداختن تاس
سکه - سکه بینداز
━━━━━━━━━━━━━━━
🏅بازی برای گرفتن مدال
━━━━━━━━━━━━━━━
✂️ سنگ کاغذ قیچی
سنگ - بازی با ربات
کاغذ - بازی با ربات
قیچی - بازی با ربات
برای هر برنده شدن یک مدال 🏅دریافت می کنید
━━━━━━━━━━━━━━━
برای تماشا مدال🏅  آمارم
━━━━━━━━━━━━━━━"""


def get_support_text(owner_name=None):
    if owner_name is None:
        owner_name = "پشتیبان"
    
    text = f"""━━━━━━━━━━━━━━━━━━
🛠️پشتیبانی ربات لِجَندِر

پشتیبان ربات: @{owner_name}
برای ارسال پیام به پشتیبان، روی دکمه زیر کلیک کنید.
━━━━━━━━━━━━━━━━━━"""

    inline_keypad = {
        "rows": [
            {
                "buttons": [
                    {
                        "id": "start_support",
                        "type": "Simple",
                        "button_text": "📩 ارسال پیام به پشتیبان"
                    }
                ]
            }
        ]
    }
    return text, inline_keypad

def get_date_time():
    now_gregorian = dt.datetime.now()
    now_jalali = jdatetime.datetime.now()
    
    persian_months = ['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند']
    persian_weekdays = {
        0: "شنبه",
        1: "یک‌شنبه",
        2: "دوشنبه",
        3: "سه‌شنبه",
        4: "چهارشنبه",
        5: "پنج‌شنبه",
        6: "جمعه"
    }
    
    weekday_name = persian_weekdays[now_jalali.weekday()]
    shamsi_date = f"{weekday_name} {now_jalali.day} {persian_months[now_jalali.month-1]} {now_jalali.year}"
    gregorian_date = now_gregorian.strftime("%A %d %B %Y")
    
    time_24 = now_jalali.strftime("%H:%M:%S")
    time_12 = now_gregorian.strftime("%I:%M:%S %p")
    time_12_fa = time_12.replace("AM", "قبل از ظهر").replace("PM", "بعد از ظهر")
    
    return {
        'shamsi': shamsi_date,
        'gregorian': gregorian_date,
        'time_24': time_24,
        'time_12': time_12_fa
    }

def learn_question(cursor, group_guid, question, answer):
    cursor.execute("REPLACE INTO chatbot (question, answer, group_guid) VALUES (%s, %s, %s)",
                   (question.lower().strip(), answer, group_guid))

def get_answer(cursor, group_guid, question):
    cursor.execute("SELECT answer FROM chatbot WHERE group_guid=%s AND question=%s", 
                   (group_guid, question.lower().strip()))
    result = cursor.fetchone()
    return result[0] if result else None

def play_game(game_name, user_guid):
    games = {'تاس': random.randint(1, 6), 'دارت': random.randint(1, 20), 'فوتبال دستی': random.choice(['پیروزی', 'باخت', 'مساوی']), 'ماشین قمار': random.randint(0, 100), 'پیش‌بینی': random.choice(['بله', 'خیر', 'شاید', 'نامشخص'])}
    if game_name in games:
        return f"🎲 نتیجه: {games[game_name]}"
    riddles = {'چیست که هرچه بیشتر از آن برداری، بزرگتر میشود؟': 'گودال', 'آن چیست که بدون زبان حرف میزند؟': 'ایمیل', 'کدام کلید باز نمی‌شود؟': 'کلید برنامه نویسی'}
    if 'معما' in game_name:
        riddle = random.choice(list(riddles.keys()))
        return f"🎭 معمای جدید:\n{riddle}\n\nپاسخ خود را بفرستید..."
    return None

def parse_time_to_seconds(time_str):
    time_str = time_str.strip()
    if time_str.isdigit():
        return int(time_str) * 60
    match = re.match(r'(\d+)\s*(ساعت|دقیقه|ثانیه)', time_str)
    if match:
        value = int(match.group(1))
        unit = match.group(2)
        if unit == 'ساعت':
            return value * 3600
        elif unit == 'دقیقه':
            return value * 60
        elif unit == 'ثانیه':
            return value
    return None