print("force_sub.py loaded")

from pyrogram import Client
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton

from config import FSUBS, MESSAGES


# =========================
# GET CHANNEL LIST
# =========================
def get_fsubs():
    result = []

    for item in FSUBS:
        try:
            cid = int(item[0]) if isinstance(item, (list, tuple)) else int(item)
            result.append(cid)
        except:
            pass

    return result


# =========================
# CHECK JOIN
# =========================
async def is_joined(client: Client, user_id: int, channel_id: int):
    try:
        member = await client.get_chat_member(channel_id, user_id)
        return member.status in ("member", "administrator", "creator")
    except:
        return False


# =========================
# BUILD BUTTON
# =========================
async def build_buttons(client: Client, not_joined):
    buttons = []

    for cid in not_joined:
        try:
            chat = await client.get_chat(cid)

            if chat.username:
                link = f"https://t.me/{chat.username}"
            else:
                link = f"https://t.me/c/{str(cid)[4:]}/1"

            buttons.append([
                InlineKeyboardButton(chat.title, url=link)
            ])

        except:
            buttons.append([
                InlineKeyboardButton("Join Channel", url="https://t.me")
            ])

    buttons.append([
        InlineKeyboardButton("Coba Lagi", callback_data="retry")
    ])

    return InlineKeyboardMarkup(buttons)


# =========================
# FORCE SUB MAIN
# =========================
async def force_sub(client: Client, message):

    if not message.from_user:
        return False

    user_id = message.from_user.id
    channels = get_fsubs()

    if not channels:
        return True

    not_joined = []

    for cid in channels:
        if not await is_joined(client, user_id, cid):
            not_joined.append(cid)

    if not_joined:
        buttons = await build_buttons(client, not_joined)

        await message.reply_text(
            MESSAGES.get("FORCE_SUB", "Kamu belum join channel"),
            reply_markup=buttons
        )

        return False

    return True