# Ultroid - UserBot
# Copyright (C) 2021-2023 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://github.com/TeamUltroid/xteam/blob/main/LICENSE>.

import base64
import ipaddress
import struct
import sys

from telethon.errors.rpcerrorlist import AuthKeyDuplicatedError
from telethon.sessions.string import _STRUCT_PREFORMAT, CURRENT_VERSION, StringSession

from xteam.configs import Var
from . import *
from .BaseClient import UltroidClient

_PYRO_FORM = {351: ">B?256sI?", 356: ">B?256sQ?", 362: ">BI?256sQ?"}

# https://github.com/pyrogram/pyrogram/blob/master/docs/source/faq/what-are-the-ip-addresses-of-telegram-data-centers.rst

DC_IPV4 = {
    1: "149.154.175.53",
    2: "149.154.167.51",
    3: "149.154.175.100",
    4: "149.154.167.91",
    5: "91.108.56.130",
}


def validate_session(session, logger=LOGS, _exit=True):
    from strings import get_string

    if session:
        # Telethon Session
        if session.startswith(CURRENT_VERSION):
            if len(session.strip()) != 353:
                logger.exception(get_string("py_c1"))
                sys.exit()
            return StringSession(session)

        # Pyrogram Session
        elif len(session) in _PYRO_FORM.keys():
            data_ = struct.unpack(
                _PYRO_FORM[len(session)],
                base64.urlsafe_b64decode(session + "=" * (-len(session) % 4)),
            )
            if len(session) in [351, 356]:
                auth_id = 2
            else:
                auth_id = 3
            dc_id, auth_key = data_[0], data_[auth_id]
            return StringSession(
                CURRENT_VERSION
                + base64.urlsafe_b64encode(
                    struct.pack(
                        _STRUCT_PREFORMAT.format(4),
                        dc_id,
                        ipaddress.ip_address(DC_IPV4[dc_id]).packed,
                        443,
                        auth_key,
                    )
                ).decode("ascii")
            )
        else:
            logger.exception(get_string("py_c1"))
            if _exit:
                sys.exit()
    logger.exception(get_string("py_c2"))
    if _exit:
        sys.exit()


"""def vc_connection(udB, ultroid_bot):
    from strings import get_string

    VC_SESSION = Var.VC_SESSION or udB.get_key("VC_SESSION")
    if VC_SESSION and VC_SESSION != Var.SESSION:
        LOGS.info("Starting up VcClient.")
        try:
            return UltroidClient(
                validate_session(VC_SESSION, _exit=False),
                log_attempt=False,
                exit_on_error=False,
            )
        except (AuthKeyDuplicatedError, EOFError):
            LOGS.info(get_string("py_c3"))
            udB.del_key("VC_SESSION")
        except Exception as er:
            LOGS.info("While creating Client for VC.")
            LOGS.exception(er)
    return ultroid_bot
"""

"""async def vc_connection(udB, ultroid_bot):
    from strings import get_string
    from telethon import TelegramClient
    from pytgcalls import PyTgCalls

    VC_SESSION = Var.VC_SESSION or udB.get_key("VC_SESSION")
    
    # Klien MTProto untuk Obrolan Suara (menggunakan Telethon)
    vc_client = None 

    if VC_SESSION and VC_SESSION != Var.SESSION:
        LOGS.info("Starting up Telethon Client for VcClient.")
        
        try:
            # 1. Buat Klien MTProto (menggunakan sesi VC)
            # Anda mungkin perlu menyesuaikan cara validasi/pembuatan sesi
            # sesuai dengan Ultroid, tapi intinya adalah mendapatkan TelegramClient.
            vc_client = TelegramClient(
                session=validate_session(VC_SESSION, _exit=False),
                api_id=Var.API_ID,  # Ganti dengan cara Ultroid mendapatkan API_ID/HASH
                api_hash=Var.API_HASH, 
                #log_attempts=False,
                system_version="UltroidVC"
            )
            # Pastikan klien terhubung
            await vc_client.start()
            
            # 2. Buat instance PyTgCalls dengan klien MTProto
            vc_call = PyTgCalls(vc_client)
            await vc_call.start()
            
            LOGS.info("PyTgCalls Client started successfully.")
            return vc_call # Mengembalikan klien PyTgCalls
            
        except (AuthKeyDuplicatedError, EOFError):
            LOGS.info(get_string("py_c3"))
            udB.del_key("VC_SESSION")
        except Exception as er:
            LOGS.info("While creating PyTgCalls Client for VC.")
            LOGS.exception(er)
            
    # Jika gagal atau tidak ada sesi VC, kembalikan bot utama atau None
    #return ultroid_bot # Atau kembalikan None, tergantung alur Ultroid

# Catatan: Fungsi ini perlu menjadi 'async def' karena menggunakan 'await'
# dan PyTgCalls/Telethon bersifat asinkron.
                
"""
