import asyncio
from telethon import functions, errors
from telethon.tl.functions.messages import ImportChatInviteRequest, ExportChatInviteRequest
from telethon.tl.functions.channels import InviteToChannelRequest, GetParticipantRequest
from telethon.errors.rpcerrorlist import UserAlreadyParticipantError
from xteam import bot
from xteam.configs import Var

ASSISTANT_ID = Var.ASSISTANT_ID

async def auto_delete(msg, delay=2):
    await asyncio.sleep(delay)
    try:
        await msg.delete()
    except Exception:
        pass

def AssistantAdd(mystic):
    async def wrapper(event):
        if not event.is_group and not event.is_channel:
            return await mystic(event)

        try:
            await event.client(GetParticipantRequest(event.chat_id, ASSISTANT_ID))
            return await mystic(event)
        except (errors.UserNotParticipantError, ValueError):
            try:
                await event.client(InviteToChannelRequest(event.chat_id, [ASSISTANT_ID]))
                status = await event.reply("**ᴀssɪsᴛᴀɴᴛ sᴜᴄᴄᴇssғᴜʟʟʏ ᴀᴅᴅᴇᴅ!**")
                asyncio.create_task(auto_delete(status, 5))
            except errors.ChatAdminRequiredError:
                try:
                    invite = await event.client(ExportChatInviteRequest(event.chat_id))
                    hash_code = invite.link.split('+')[-1] if '+' in invite.link else invite.link.split('/')[-1]
                    await bot(ImportChatInviteRequest(hash_code))
                    status = await event.reply("**ᴀssɪsᴛᴀɴᴛ sᴜᴄᴄᴇssғᴜʟʟʏ ᴊᴏɪɴᴇᴅ!**")
                    asyncio.create_task(auto_delete(status, 5))
                except Exception:
                    error = await event.reply("❌ **ᴇʀʀᴏʀ**: Saya butuh hak admin (Add Users) untuk mengundang assistant!")
                    asyncio.create_task(auto_delete(error, 10))
                    return
            except Exception as e:
                error = await event.reply(f"❌ **ᴀssɪsᴛᴀɴᴛ ғᴀɪʟᴇᴅ ᴛᴏ ᴊᴏɪɴ**\n\n**Note**: `{e}`")
                asyncio.create_task(auto_delete(error, 10))
                return
        except errors.ChatAdminRequiredError:
            return await mystic(event)
        except Exception:
            return await mystic(event)
                
        return await mystic(event)

    return wrapper
                
