# Made for Ultroid by dot arc!
# Base plugin and Word DB from Catub.

"""
**On9 Bot Hack!**

> `{i}on9 on`
> `{i}on9 off`
"""

from asyncio import sleep
from json import loads, dumps
from pathlib import Path
from random import choice, randint

from telethon.events import NewMessage

from . import async_searcher, LOGS, ultroid_cmd, udB


WORD_DB = "https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt"
BOT_ID = [840338206]


async def get_json_file(file):
    word_list = await async_searcher(WORD_DB)
    data = {}
    for word in word_list.splitlines():
        word = word.strip().lower()
        first_letter = word[0]
        if first_letter in data:
            data[first_letter].append(word)
        else:
            data[first_letter] = [word]
    del word_list
    file.write_text(dumps(data, indent=2))


async def get_text(char, count):
    file = Path("words.json")
    try:
        if not file.is_file():
            await get_json_file(file)
        words = filter(
            lambda i: len(i) in range(count, count + 5),
            loads(file.read_text()).get(char),
        )
        return choice(tuple(words))
    except Exception:
        LOGS.warning("Error in on9 - get_text", exc_info=True)


def find_data(text):
    # logic from catub
    t1 = text.split("\n", 2)[1].split(" ")
    letter = t1[5].replace("_", "")
    count = int(t1[10])
    return letter, count


async def on9_hack(e):
    if e.is_group and str(e.text).startswith("Turn: "):
        char, count = find_data(e.text.lower())
        if word := await get_text(char, count):
            await sleep(3)
            async with e.client.action(e.chat_id, "typing"):
                await sleep(2 if len(word) <= 5 else max(4, len(word) // 3))
                await e.client.send_message(
                    e.chat_id, word.capitalize(), reply_to=choice((None, e.id))
                )


@ultroid_cmd(pattern="on9( (.*)|$)", fullsudo=True)
async def on9_setup(e):
    msg = await e.eor("`checking...`")
    args = e.pattern_match.group(2)
    key = udB.get_key("ON9_HACKS")
    if args == "on":
        if key:
            return await msg.edit("`On9 hack is already enabled..`")
        udB.set_key("ON9_HACKS", True)
        ultroid_bot.add_event_handler(
            on9_hack, NewMessage(from_users=BOT_ID, func=lambda e: e.mentioned)
        )
        await msg.edit("`On9 hack is Running..`")
    elif args == "off":
        if not key:
            return await msg.edit("`On9 hack is already disabled..`")
        udB.del_key("ON9_HACKS")
        ultroid_bot.remove_event_handler(on9_hack)
        await msg.edit("`Stopped On9 hack..`")
    else:
        status = "Enabled" if key else "Disabled"
        txt = f"**On9 Hack is {status}!** \n\n`Toggle with .on9 <on/off>`"
        await msg.edit(txt)


if udB.get_key("ON9_HACKS"):
    LOGS.info("Loading on9 hack..")
    ultroid_bot.add_event_handler(
        on9_hack, NewMessage(from_users=BOT_ID, func=lambda e: e.mentioned)
    )
