import asyncio
import threading
import time

from loguru import logger
from opentele.api import API
from telethon.errors import SessionPasswordNeededError, PhoneCodeInvalidError, RPCError, PhoneNumberBannedError, \
    PasswordHashInvalidError
from telethon import TelegramClient

from models.tg_phone_devices import TgPhoneDevices


async def create_telegram_client(server_type):
    """
    创建并配置 Telegram 客户端
    """

    # gw.dataimpulse.com:824:14fa7e7aa8280a914611__cr.gb:f1c1501b6b535c19
    # 定义代理
    PROXY_CONFIG = {
        'proxy_type': 'http',  # 或 'socks4'，具体看你的代理类型
        'addr': '192.168.50.220',  # 代理服务器地址
        'port': 10809,  # 代理服务器端口
        'username': '',  # 如果有用户名，填写
        'password': ''  # 如果有密码，填写
    }

    client = TelegramClient(
        fr"C:\sessions\{server_type.phone}",
        api_id=server_type.api_id,
        api_hash=server_type.api_hash,
        device_model=server_type.device_model,
        system_version=server_type.system_version,
        app_version=server_type.app_version,
        system_lang_code=server_type.system_lang_code,
        lang_code=server_type.lang_code,
        proxy=PROXY_CONFIG
    )
    return client


async def main(tg_info):
    # 创建 Telegram 客户端

    logger.info(f"账号 {tg_info.phone}，开始修改》》》")

    client = await create_telegram_client(tg_info)

    try:
        await client.connect()

        if await client.is_user_authorized():
            current_password = tg_info.code
            new_password = "Qasdasd123.0"

            try:
                # time.sleep(5)
                await client.edit_2fa(current_password=current_password, new_password=new_password)
                logger.info(f"账号 {tg_info.phone}，修改成功！！！")

                tg_info.to_code = new_password
                tg_info.save(only=[TgPhoneDevices.to_code])

            except PasswordHashInvalidError:
                logger.error(f"账号 {tg_info.phone}，操作失败，原始2FA不对！！！")

        else:
            logger.error(f"账号 {tg_info.phone}，当前号码已死！！！")

    except PhoneNumberBannedError:
        logger.error(f"账号 {tg_info.phone}，账号以死！！！")

        tg_info.is_valid_session = -1
        tg_info.save(only=[TgPhoneDevices.is_valid_session])

    finally:
        await client.disconnect()


def main1(tg_info):
    asyncio.run(main(tg_info))


if __name__ == '__main__':

    for tg_info in TgPhoneDevices().select().where(
            TgPhoneDevices.to_code.is_null(),
            TgPhoneDevices.is_valid_session == 1,
            # TgPhoneDevices.server_ip.is_null(),
            TgPhoneDevices.create_time > '2025-06-06 12:04:19',
            # TgPhoneDevices.create_time < '2025-02-28 23:00:00',
    ):
        # asyncio.run(main(tg_info))

        threading.Thread(target=main1, args=(tg_info,)).start()
        time.sleep(1)
