import asyncio
from urllib.parse import unquote

from telethon.tl.functions.channels import JoinChannelRequest
from telethon.tl.functions.messages import RequestWebViewRequest
from telethon import TelegramClient
from telethon.tl.types import InputPeerUser

from models.tg_phone_devices import TgPhoneDevices


async def create_telegram_client(tg_info):
    """
    创建并配置 Telegram 客户端
    """
    client = TelegramClient(
        fr"C:\sessions\{tg_info.phone}",
        api_id=tg_info.api_id,
        api_hash=tg_info.api_hash,
        device_model=tg_info.device_model,
        system_version=tg_info.system_version,
        app_version=tg_info.app_version,
        system_lang_code=tg_info.system_lang_code,
        lang_code=tg_info.lang_code,
    )
    return client


async def get_token(client):
    # 调用 RequestAppWebView，传递所需的参数
    bot_name_lst = [
        # "BlumCryptoBot",
        # 'DepinSimBot'
        # 'OfficialBananaBot',
        "tomowalletbot"
    ]
    for bot_name in bot_name_lst:
        # bot_name = "DepinSimBot"
        bot = await client.get_entity(bot_name)
        if bot_name == "DepinSimBot":
            channel_name = 'depinsim'

            channel = await client.get_entity(channel_name)
            # 加入频道
            await client(JoinChannelRequest(channel))

        # 发送消息（示例：开始对话）
        await client.send_message(bot, '/start')

        peer = InputPeerUser(bot.id, bot.access_hash)
        web_view = await client(
            RequestWebViewRequest(
                peer=peer,
                bot=peer,
                platform='android',
                from_bot_menu=False,
                url='https://tomotg.tomo.inc/',
            )
        )

        auth_url = web_view.url
        print(auth_url)
        query = unquote(string=unquote(string=auth_url.split('tgWebAppData=')[1].split('&tgWebAppVersion')[0]))
        print(query)

    return True


async def set_link(client):
    # 检查用户是否已授权
    if await client.is_user_authorized():
        # 使用邀请码启动机器人对话
        # 'bot_username' 是机器人的用户名，通常以 'bot' 结尾
        # 'invite_code' 替换为你的邀请码，如果不需要邀请码则省略此参数
        bot_username = 'TimeFarmCryptoBot'
        invite_code = '1ll25QcyYLilP5NQF'
        # https://t.me/TimeFarmCryptoBot?start=1ll25QcyYLilP5NQF

        await client.send_message(bot_username, f'/start {invite_code}')


async def main(tg_info):
    # 创建 Telegram 客户端
    client = await create_telegram_client(tg_info)

    await client.connect()

    await get_token(client)
    await client.disconnect()


if __name__ == '__main__':
    tg_info = TgPhoneDevices().get_or_none(
        TgPhoneDevices.phone == "8617120751158",
    )

    asyncio.run(main(tg_info))
