# utils.py
import re
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.helpers import escape_markdown
from config import NAME_FORMATS, CHANNEL_ID, MESSAGES
from database import get_setting, get_sponsor_channels

async def check_membership(bot, user_id: int):
    """بررسی عضویت کاربر در کانال اصلی"""
    try:
        m = await bot.get_chat_member(CHANNEL_ID, user_id)
        if m.status in ("member", "administrator", "creator"):
            return True, []
        return False, [(CHANNEL_ID, "چنل اصلی")]
    except Exception:
        return False, [(CHANNEL_ID, "چنل اصلی")]

def join_keyboard(not_joined: list, pending_mode: str = "") -> InlineKeyboardMarkup:
    """ساخت کیبورد عضویت"""
    keyboard = []
    for ch_id, ch_name in not_joined:
        if str(ch_id).startswith("@"):
            link = f"https://t.me/{ch_id.lstrip('@')}"
        else:
            link = f"https://t.me/c/{str(ch_id).lstrip('-100')}"
        keyboard.append([InlineKeyboardButton(f"➕ عضویت در {ch_name}", url=link)])
    keyboard.append([InlineKeyboardButton(MESSAGES["btn_joined"], callback_data="check_joined")])
    return InlineKeyboardMarkup(keyboard)

def format_user_name(user, fmt: str) -> str:
    """فرمت کردن نام کاربر بر اساس تنظیمات"""
    first = user.first_name or ""
    last = user.last_name or ""
    full = f"{first} {last}".strip()
    username = f"@{user.username}" if user.username else full
    uid = user.id
    
    # انتخاب فرمت
    format_template = NAME_FORMATS.get(fmt, NAME_FORMATS["1"])
    
    if fmt == "10":
        return ""
    
    # تعیین متن نمایشی
    if fmt in ["1", "3", "5", "6", "8", "9"]:
        display_name = username
    else:  # 2, 4, 7
        display_name = full
    
    return format_template.format(escape_markdown(display_name, version=2), uid)

async def send_media_to_channel(bot, row, caption):
    """ارسال مدیا به کانال"""
    _, user_id, first_name, username, file_id, \
    performer, title, duration, is_voice, is_anon, _ = row
    
    if is_voice:
        return await bot.send_voice(
            chat_id=CHANNEL_ID,
            voice=file_id,
            caption=caption,
            parse_mode=None,
        )
    else:
        return await bot.send_audio(
            chat_id=CHANNEL_ID,
            audio=file_id,
            caption=caption,
            parse_mode=None,
            performer=performer or None,
            title=title or None,
            duration=duration or None,
        )