import asyncio
import random
import threading
import time

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

from models.tg_phone_devices import TgPhoneDevices, TgPhoneDevices1
from tg.text import main1111


async def get_device_info():
    """
    获取设备信息
    """
    NewApi = API.TelegramDesktop.Generate(system="windows")
    return {
        "api_id": NewApi.api_id,
        "api_hash": NewApi.api_hash,
        "device_model": NewApi.device_model,
        'system_version': 'Windows 10',
        "app_version": "6.3.4 x64",
        "lang_code": NewApi.lang_code,
        "system_lang_code": NewApi.system_lang_code
    }


async def create_telegram_client(api_id, api_hash, phone_num, server_type1, server):
    """
    创建并配置 Telegram 客户端
    """

    # 定义代理
    proxy = {
        'proxy_type': server.proxy_type,  # 或 'socks4'，具体看你的代理类型
        'addr': "192.168.1.79",  # 代理服务器地址
        'port': int(server.port),  # 代理服务器端口
        'username': server.user if server.user else "",  # 如果有用户名，填写
        'password': server.pwd if server.pwd else ""  # 如果有密码，填写
    }

    client = TelegramClient(
        fr"sessions\{phone_num}",
        api_id=api_id,
        api_hash=api_hash,
        device_model=server_type1.device_model,
        system_version=server_type1.system_version,
        app_version=server_type1.app_version,
        system_lang_code=server_type1.system_lang_code,
        lang_code=server_type1.lang_code,
        proxy=proxy
    )
    return client


async def login_telegram(client, phone_num):
    """
    处理登录流程
    """
    try:

        sent_code_info = await client.send_code_request(phone_num)
        # code = input("请输入验证码：")

        time.sleep(3)
        code = await main1111(phone=phone_num)

        try:
            await client.sign_in(phone=phone_num, code=code)
        except PhoneCodeInvalidError:
            logger.error("验证码无效，请重试")
            return False
        except SessionPasswordNeededError:
            # password = input("请输入密码：")
            await client.sign_in(password="Haxi@123456@")

        me = await client.get_me()
        logger.info(f'账号 {phone_num} -- {me.first_name} 登录成功！')

        return True

    except (RPCError, Exception) as e:
        logger.error(f'登录失败，错误信息：{e}')
        return False

    finally:
        await client.disconnect()


async def main(device):
    # 读取设备信息和 API 参数
    device_info = await get_device_info()
    api_id = device_info["api_id"]
    api_hash = device_info["api_hash"]

    # area_code = input("请输入区号：")
    # phone_number = input("请输入电话号码：")

    area_code = device.area_code
    phone_number = device.phone_number

    server, server_type = TgPhoneDevices().get_or_create(
        phone_number=phone_number,
    )

    server1, server_type = TgPhoneDevices1().get_or_create(
        phone_number=phone_number,
    )

    server1.area_code = area_code
    server1.api_id = api_id
    server1.api_hash = api_hash
    # 这里我加了一行代码 by rachel 成功默认为1
    server1.is_valid_session = '1'
    server1.device_model = device_info["device_model"]
    server1.system_version = device_info["system_version"]
    server1.app_version = device_info["app_version"]
    server1.system_lang_code = device_info["system_lang_code"]
    server1.lang_code = device_info["lang_code"]
    server1.phone = area_code + phone_number

    server1.proxy_type = server.proxy_type
    server1.addr = server.addr
    server1.port = server.port

    server1.save()

    # 创建 Telegram 客户端
    phone = area_code + phone_number
    client = await create_telegram_client(api_id, api_hash, phone, server1, server)

    await client.connect()

    if await client.is_user_authorized():
        me = await client.get_me()
        logger.info(f'账号 {phone_number} -- {me.first_name} 登录成功！')
    else:

        # 登录 Telegram
        if await login_telegram(client, phone):
            logger.info("Telegram 客户端操作完成")

            server1.is_valid_session = 1
            server1.save()


        else:
            logger.error("Telegram 登录失败")

            server1.is_valid_session = 0
            server1.save()


def run_main(device):
    asyncio.run(main(device))


if __name__ == '__main__':
    # 筛选出 is_valid_session 为 1 的记录
    valid_devices = TgPhoneDevices.select().where(TgPhoneDevices.is_valid_session == 1)

    # 将查询结果转换为列表
    valid_devices_list = list(valid_devices)

    # 随机选择 100 条记录，如果记录总数不足 100 条，则选择全部记录
    random_devices = random.sample(valid_devices_list, min(1524, len(valid_devices_list)))

    # 输出结果
    for device in random_devices:
        threading.Thread(target=run_main, args=(device,)).start()
        time.sleep(0.5)
