import requests
import os
import sys
import jwt
import pickle
import json
import binascii
import time
import urllib3
import base64
import datetime
import re
import socket
import threading
from datetime import datetime
from google.protobuf.timestamp_pb2 import Timestamp
from concurrent.futures import ThreadPoolExecutor
from threading import Thread
from google_play_scraper import app
# Relative import from the same package
from .xPARA import *

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# ----------------------------------------------------------------------
# The background thread that previously ran ToK() has been removed.
# The following functions are kept for compatibility with the original
# code base, but they are not required by the get_account_info() function.
# ----------------------------------------------------------------------

def GeT_OB():
    """Fetch the current OB version from a public endpoint."""
    try:
        url = "https://version.freefire.info/mscrtfree/live/ver.php?version=2.114.18&lang=en&device=android&channel=android_max&appstore=googleplay_max&region=DEFAULT&whitelist_version=1.3.0&whitelist_sp_version=1.0.0&device_name=samsung%20SM-A165F&device_CPU=ARM64%20FP%20ASIMD%20AES&device_GPU=Mali-G57%20MC2&device_mem=3621"
        response = requests.get(url)
        ob = response.json()["latest_release_version"]
        return ob
    except:
        return None

def obv():
    """Return the OB version, retrying on failure."""
    ob = GeT_OB()
    if ob is None:
        print('Error FeTCinG OB VErsiON !')
        return obv()
    else:
        print("OB VERSION = > {}".format(ob))
        return ob

def AuToUpDaTE():
    """
    Retrieve the current Free Fire version from Google Play and the server URL.
    Returns: (server_url, ob_version, game_version)
    """
    result = app('com.dts.freefireth',
                lang="fr",
                country='fr')
    version = result['version']
    r = requests.get(f'https://bdversion.ggbluefox.com/live/ver.php?version={version}&lang=ar&device=android&channel=android&appstore=googleplay&region=ME&whitelist_version=1.3.0&whitelist_sp_version=1.0.0&device_name=google%20G011A&device_CPU=ARMv7%20VFPv3%20NEON%20VMH&device_GPU=Adreno%20(TM)%20640&device_mem=1993').json()
    url, ob = r['server_url'], r['latest_release_version']
    return url, ob, version

# The following functions are not needed for the library but are kept for
# completeness. They may be used in other parts of the original code base.
# Note: Some of them reference GeTToK(), which is no longer defined.
# If you need them, you must define a GeTToK() function that returns a valid token.
# They will not affect get_account_info() unless called directly.

def lag(JWT):
    url = "https://clientbp.ggblueshark.com/RequestJoinClan"
    headers = {
        "Accept-Encoding": "gzip",
        "Authorization": f"Bearer {JWT}",
        "Connection": "Keep-Alive",
        "Content-Type": "application/x-www-form-urlencoded",
        "Host": "clientbp.ggblueshark.com",
        "ReleaseVersion": "OB50",
        "User-Agent": "Dalvik/2.1.0 (Linux; U; Android 9; G011A Build/PI)",
        "X-GA": "v1 1",
        "X-Unity-Version": "2018.4.11f1"
    }
    data = bytes.fromhex("BA 1F 7A E7 D0 9D AC 6D A3 50 41 72 94 B6 E5 04")
    response = requests.post(url, headers=headers, data=data)
    print("Status:", response.status_code)
    print("Response:", response.text)

def equipe_emote(JWT):
    url = "https://clientbp.ggblueshark.com/ChooseEmote"
    headers = {
        "Accept-Encoding": "gzip",
        "Authorization": f"Bearer {JWT}",
        "Connection": "Keep-Alive",
        "Content-Type": "application/x-www-form-urlencoded",
        "Expect": "100-continue",
        "Host": "clientbp.ggblueshark.com",
        "ReleaseVersion": "OB50",
        "User-Agent": "Dalvik/2.1.0 (Linux; U; Android 9; G011A Build/PI)",
        "X-GA": "v1 1",
        "X-Unity-Version": "2018.4.11f1",
    }
    data = bytes.fromhex("CA F6 83 22 2A 25 C7 BE FE B5 1F 59 54 4D B3 13")
    r = requests.post(url, headers=headers, data=data)

def Likes(id):
    try:
        text = requests.get(f"https://tokens-asfufvfshnfkhvbb.francecentral-01.azurewebsites.net/ReQuesT?id={id}&type=likes").text
        get = lambda p: re.search(p, text)
        name, lvl, exp, lb, la, lg = (get(r).group(1) if get(r) else None for r in 
            [r"PLayer NamE\s*:\s*(.+)", r"PLayer SerVer\s*:\s*(.+)", r"Exp\s*:\s*(\d+)", 
             r"LiKes BeFore\s*:\s*(\d+)", r"LiKes After\s*:\s*(\d+)", r"LiKes GiVen\s*:\s*(\d+)"])
        return name, f"{lvl}" if lvl else None, int(lb) if lb else None, int(la) if la else None, int(lg) if lg else None
    except:
        return None, None, None, None, None

def Requests_SPam(id):
    Api = requests.get(f'https://tokens-asfufvfshnfkhvbb.francecentral-01.azurewebsites.net/ReQuesT?id={id}&type=spam')        
    if Api.status_code in [200, 201] and '[SuccessFuLy] -> SenDinG Spam ReQuesTs !' in Api.text:
        return True
    else:
        return False

def GeT_Name(uid, Token):
    # This function uses GeTToK() which is not defined. To avoid errors,
    # you must provide a valid token or replace GeTToK() with your own logic.
    data = bytes.fromhex(EnC_AEs(f"08{EnC_Uid(uid, Tp='Uid')}1007"))
    url = "https://clientbp.common.ggbluefox.com/GetPlayerPersonalShow"
    headers = {
        'X-Unity-Version': '2018.4.11f1',
        'ReleaseVersion': 'OB50',
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-GA': 'v1 1',
        'Authorization': f'Bearer {GeTToK()}',
        'Content-Length': '16',
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 7.1.2; ASUS_Z01QD Build/QKQ1.190825.002)',
        'Host': 'clientbp.ggblueshark.com',
        'Connection': 'Keep-Alive',
        'Accept-Encoding': 'gzip'
    }
    response = requests.post(url, headers=headers, data=data, verify=False)
    if response.status_code in (200, 201):
        packet = binascii.hexlify(response.content).decode('utf-8')
        RedZed_data = json.loads(DeCode_PackEt(packet))      
        try:
            a1 = RedZed_data["1"]["data"]["3"]["data"]
            return a1
        except:
            return ''  
    else:
        return ''

def GeT_PLayer_InFo(uid, Token):
    # Similarly, this function relies on GeTToK().
    data = bytes.fromhex(EnC_AEs(f"08{EnC_Uid(uid, Tp='Uid')}1007"))
    url = "https://clientbp.common.ggbluefox.com/GetPlayerPersonalShow"
    headers = {
        'X-Unity-Version': '2018.4.11f1',
        'ReleaseVersion': 'OB50',
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-GA': 'v1 1',
        'Authorization': f'Bearer {GeTToK()}',
        'Content-Length': '16',
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 7.1.2; ASUS_Z01QD Build/QKQ1.190825.002)',
        'Host': 'clientbp.ggblueshark.com',
        'Connection': 'Keep-Alive',
        'Accept-Encoding': 'gzip'}
    response = requests.post(url, headers=headers, data=data, verify=False)
    if response.status_code in (200, 201):
        packet = binascii.hexlify(response.content).decode('utf-8')
        RedZed_data = json.loads(DeCode_PackEt(packet))
        NoCLan = False   
        try:        
            a1 = str(RedZed_data["1"]["data"]["1"]["data"])
            a2 = RedZed_data["1"]["data"]["21"]["data"]
            a3 = RedZed_data["1"]["data"]["3"]["data"]
            player_server = RedZed_data["1"]["data"]["5"]["data"]
            player_bio = RedZed_data["9"]["data"]["9"]["data"]
            player_level = RedZed_data["1"]["data"]["6"]["data"]
            account_date = datetime.fromtimestamp(RedZed_data["1"]["data"]["44"]["data"]).strftime("%I:%M %p - %d/%m/%y")
            last_login = datetime.fromtimestamp(RedZed_data["1"]["data"]["24"]["data"]).strftime("%I:%M %p - %d/%m/%y")
            try:
                clan_id = RedZed_data["6"]["data"]["1"]["data"]
                clan_name = RedZed_data["6"]["data"]["2"]["data"]
                clan_leader = RedZed_data["6"]["data"]["3"]["data"]
                clan_level = RedZed_data["6"]["data"]["4"]["data"]
                clan_members_num = RedZed_data["6"]["data"]["6"]["data"]
                clan_leader_name = RedZed_data["7"]["data"]["3"]["data"]                       
            except:
                NoCLan = True
            if NoCLan:
                a = f'''
[b][c][90EE90] [SuccessFully] - Get PLayer s'InFo !

[FFFF00][1] - ProFile InFo :
[ffffff]    
 Name : {a3}
 Uid : {xMsGFixinG(a1)}
 Likes : {xMsGFixinG(a2)}
 LeveL : {player_level}
 Server : {player_server}
 Bio : {player_bio}
 Creating : {account_date}
 LasT LoGin : {last_login}
 
[90EE90]Dev : PARAHEX Team OfficieL\n'''
                a = a.replace('[i]','')
                return a
            else:
                a = f'''
[b][c][90EE90] [SuccessFully] - Get PLayer s'InFo !

[FFFF00][1] - ProFile InFo :
[ffffff]    
 Name : {a3}
 Uid : {xMsGFixinG(a1)}
 Likes : {xMsGFixinG(a2)}
 LeveL : {player_level}
 Server : {player_server}
 Bio : {player_bio}
 Creating : {account_date}
 LasT LoGin : {last_login}

[b][c][FFFF00][2] - Guild InFo :
[ffffff]
 Guild Name : {clan_name}
 Guild Uid : {xMsGFixinG(clan_id)}
 Guild LeveL : {clan_level}
 Guild Members : {clan_members_num}
 Leader s'Uid : {xMsGFixinG(clan_leader)}
 Leader s'Name : {clan_leader_name}

  [90EE90]Dev : PARAHEX Team OfficieL\n'''
                a = a.replace('[i]','')
                return a
        except Exception as e:
            return f'\n[b][c][FFD700]FaiLEd GeTinG PLayer InFo !\n'
    else:
        return f'\n[b][c][FFD700]FaiLEd GeTinG PLayer InFo !\n'
    
def DeLet_Uid(id, Tok):
    print(f' Done FuckinG > {id} ')
    url = 'https://clientbp.common.ggbluefox.com/RemoveFriend'
    headers = {
        'X-Unity-Version': '2018.4.11f1',
        'ReleaseVersion': 'OB50',
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-GA': 'v1 1',
        'Authorization': f'Bearer {Tok}',
        'Content-Length': '16',
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 7.1.2; ASUS_Z01QD Build/QKQ1.190825.002)',
        'Host': 'clientbp.ggblueshark.com',
        'Connection': 'Keep-Alive',
        'Accept-Encoding': 'gzip'}
    data = bytes.fromhex(EnC_AEs(f"08a7c4839f1e10{EnC_Uid(id, Tp='Uid')}"))
    ResPonse = requests.post(url, headers=headers, data=data, verify=False)    
    if ResPonse.status_code == 400 and 'BR_FRIEND_NOT_SAME_REGION' in ResPonse.text:
        return f'[b][c]Id : {xMsGFixinG(id)} Not In Same Region !'
    elif ResPonse.status_code == 200:
        return f'[b][c]Good Response Done Delete Id : {xMsGFixinG(id)} !'
    else:
        return f'[b][c]Erorr !'
                                                        
def ChEck_The_Uid(id):
    Api = requests.get("https://panel-g2ccathtf6gdcmdw.polandcentral-01.azurewebsites.net/Uids")
    if Api.status_code not in [200, 201]: 
        return False    
    lines = Api.text.splitlines()    
    for i, line in enumerate(lines):
        if f' - Uid : {id}' in line:
            expire, status = None, None
            for sub_line in lines[i:]:
                if "Expire In" in sub_line: 
                    expire = re.search(r"Expire In\s*:\s*(.*)", sub_line).group(1).strip()
                if "Status" in sub_line: 
                    status = re.search(r"Status\s*:\s*(\w+)", sub_line).group(1)
                if expire and status:
                    return status, expire
            return False
    return False