from re import findall
from re import sub as re_sub

from pykeyboard import InlineKeyboard
from pyrogram.types import InlineKeyboardButton as Ikb


def ikb(data: dict, row_width: int = 2):
    return keyboard(data.items(), row_width=row_width)


def get_urls_from_text(text: str) -> bool:
    regex = r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]

                [.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(

                \([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\

                ()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))""".strip()

    return [x[0] for x in findall(regex, str(text))]


is_url = get_urls_from_text


chat_filters_group = 1


def keyboard(buttons_list, row_width: int = 2):
    buttons = InlineKeyboard(row_width=row_width)

    data = [
        (
            Ikb(text=str(i[0]), callback_data=str(i[1]))
            if not is_url(i[1])
            else Ikb(text=str(i[0]), url=str(i[1]))
        )
        for i in buttons_list
    ]

    buttons.add(*data)

    return buttons


def extract_text_and_keyb(ikb, text: str, row_width: int = 2):
    keyboard = {}

    try:
        text = text.strip()

        if text.startswith("`"):
            text = text[1:]

        if text.endswith("`"):
            text = text[:-1]

        text, keyb = text.split("~")

        keyb = findall(r"\[.+\,.+\]", keyb)

        for btn_str in keyb:
            btn_str = re_sub(r"[\[\]]", "", btn_str)

            btn_str = btn_str.split(",")

            btn_txt, btn_url = btn_str[0], btn_str[1].strip()

            if not get_urls_from_text(btn_url):
                continue

            keyboard[btn_txt] = btn_url

        keyboard = ikb(keyboard, row_width)

    except Exception:
        return

    return text, keyboard
