import requests,re,time,json,random,fake_useragent
from user_agent import generate_user_agent as ggb
from random import choice as cc
from random import randrange as rr
def fetch_random_device():
    url = "https://raw.githubusercontent.com/Z4usXcode/-/main/devices.txt"
    response = requests.get(url)
    response.raise_for_status()
    
    lines = response.text.strip().splitlines()
    if not lines:
        raise ValueError("Dosya boş.")
    line = random.choice(lines)    
    parts = line.strip().split(":")
    if len(parts) != 7:
        raise ValueError("Satır beklenen formatta değil.")    
    return {
        "iid": parts[0],
        "did": parts[1],
        "type": parts[2],
        "brand": parts[3],
        "os_version": parts[4],
        "cdid": parts[5],
        "odid": parts[6],
    }
def info(username):
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Android 10; Pixel 3 Build/QKQ1.200308.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/125.0.6394.70 Mobile Safari/537.36 trill_350402 JsSdk/1.0 NetType/MOBILE Channel/googleplay AppName/trill app_version/35.3.1 ByteLocale/en ByteFullLocale/en Region/IN AppId/1180 Spark/1.5.9.1 AppVersion/35.3.1 BytedanceWebview/d8a21c6",
    }
    try:
        tikinfo = requests.get(f'https://www.tiktok.com/@{username}', headers=headers).text
        data = json.loads(re.search(r'<script id="__UNIVERSAL_DATA_FOR_REHYDRATION__" type="application/json">(.*?)</script>', tikinfo).group(1))
        user = data['__DEFAULT_SCOPE__']['webapp.user-detail']['userInfo']['user']
        stats = data['__DEFAULT_SCOPE__']['webapp.user-detail']['userInfo']['stats']
        
        return {
            'id': user['id'],
            'username': user['uniqueId'],
            'name': user['nickname'],
            'verified': user['verified'],
            'private': user['privateAccount'],
            'create_time': time.strftime('%Y-%m-%d', time.localtime(user['createTime'])),
            'videos': stats['videoCount'],
            'followers': stats['followerCount'],
            'following': stats['followingCount'],
            'likes': stats['heartCount']
        }
    except Exception as e:
        print(f"Error getting user info: {e}")
        return None

def check_tiktok_registered(email):
    response = requests.post(
        'https://web-sg.tiktok.com/passport/web/user/check_email_registered?multi_login=1&did=&locale=ar&app_language=en&aid=1459&account_sdk_source=web&sdk_version=2.1.11-tiktokbeta.3&language=en&verifyFp=&standalone_aid=&shark_extra=%7B%22aid%22:1459,%22app_name%22:%22Tik_Tok_Login%22,%22channel%22:%22tiktok_web%22,%22device_platform%22:%22web_mobile%22,%22device_id%22:%227597508492069586453%22,%22region%22:%22IQ%22,%22priority_region%22:%22%22,%22os%22:%22android%22,%22referer%22:%22https:%2F%2Fwww.tiktok.com%2Fprofile%22,%22root_referer%22:%22https:%2F%2Fwww.google.com%2F%22,%22cookie_enabled%22:true,%22screen_width%22:400,%22screen_height%22:889,%22browser_language%22:%22ar-IQ%22,%22browser_platform%22:%22Linux+armv81%22,%22browser_name%22:%22Mozilla%22,%22browser_version%22:%225.0+(Linux%3B+Android+10%3B+K)+AppleWebKit%2F537.36+(KHTML,+like+Gecko)+Chrome%2F132.0.0.0+Mobile+Safari%2F537.36%22,%22browser_online%22:true,%22verifyFp%22:%22verify_mkmwxx0p_ZkPLAvMH_3cNy_4QzT_BKNm_1cM1BmpAbadP%22,%22app_language%22:%22ar%22,%22webcast_language%22:%22ar%22,%22tz_name%22:%22Asia%2FBaghdad%22,%22is_page_visible%22:true,%22focus_state%22:true,%22is_fullscreen%22:false,%22history_len%22:39,%22user_is_login%22:false,%22data_collection_enabled%22:false%7D&msToken=',
        headers={
            'user-agent': fake_useragent.FakeUserAgent().random
        },
        data={'email': email}
    )
    return response.text

yy = 'azertyuiopmlkjhgfdsqwxcvbn'
def Gmail(email):
    try:
        n1 = ''.join(cc(yy) for i in range(rr(6, 9)))
        n2 = ''.join(cc(yy) for i in range(rr(3, 9)))
        host = ''.join(cc(yy) for i in range(rr(15, 30)))
        
        he3 = {
            "accept": "*/*",
            "accept-language": "ar-IQ,ar;q=0.9,en-IQ;q=0.8,en;q=0.7,en-US;q=0.6",
            "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
            "google-accounts-xsrf": "1",
            'user-agent': str(ggb()),
        }
        
        res1 = requests.get(
            'https://accounts.google.com/signin/v2/usernamerecovery?flowName=GlifWebSignIn&flowEntry=ServiceLogin&hl=en-GB', 
            headers=he3
        )
        
        tok = re.search(r'data-initial-setup-data="%.@.null,null,null,null,null,null,null,null,null,&quot;(.*?)&quot;,null,null,null,&quot;(.*?)&', res1.text).group(2)
        
        cookies = {'__Host-GAPS': host}
        headers = {
            'authority': 'accounts.google.com',
            'accept': '*/*',
            'accept-language': 'en-US,en;q=0.9',
            'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'google-accounts-xsrf': '1',
            'origin': 'https://accounts.google.com',
            'referer': 'https://accounts.google.com/signup/v2/createaccount?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2Fu%2F0%2F&theme=mn',
            'user-agent': ggb(),
        }
        
        data = {
            'f.req': f'["{tok}","{n1}","{n2}","{n1}","{n2}",0,0,null,null,"web-glif-signup",0,null,1,[],1]',
            'deviceinfo': '[null,null,null,null,null,"NL",null,null,null,"GlifWebSignIn",null,[],null,null,null,null,2,null,0,1,"",null,null,2,2]',
        }
        
        response = requests.post(
            'https://accounts.google.com/_/signup/validatepersonaldetails',
            cookies=cookies,
            headers=headers,
            data=data,
        )
        
        tl = str(response.text).split('",null,"')[1].split('"')[0]
        host = response.cookies.get_dict()['__Host-GAPS']
        
    except Exception as e:
        print(f"Token alma hatası: {e}")
        return "vpn"
    
    # Email kontrol işlemi
    try:
        if '@' in email:
            email = str(email).split('@')[0]

        cookies = {'__Host-GAPS': host}
        headers = {
            'authority': 'accounts.google.com',
            'accept': '*/*',
            'accept-language': 'en-US,en;q=0.9',
            'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'google-accounts-xsrf': '1',
            'origin': 'https://accounts.google.com',
            'referer': f'https://accounts.google.com/signup/v2/createusername?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2Fu%2F0%2F&TL={tl}',
            'user-agent': ggb(),
        }

        params = {'TL': tl}
        data = (
            'continue=https%3A%2F%2Fmail.google.com%2Fmail%2Fu%2F0%2F&ddm=0&flowEntry=SignUp&service=mail&theme=mn'
            f'&f.req=%5B%22TL%3A{tl}%22%2C%22{email}%22%2C0%2C0%2C1%2Cnull%2C0%2C5167%5D&azt=AFoagUUtRlvV928oS9O7F6eeI4dCO2r1ig%3A1712322460888&cookiesDisabled=false&deviceinfo=%5Bnull%2Cnull%2Cnull%2Cnull%2Cnull%2C%22NL%22%2Cnull%2Cnull%2Cnull%2C%22GlifWebSignIn%22%2Cnull%2C%5B%5D%2Cnull%2Cnull%2Cnull%2Cnull%2C2%2Cnull%2C0%2C1%2C%22%22%2Cnull%2Cnull%2C2%2C2%5D&gmscoreversion=undefined&flowName=GlifWebSignIn&'
        )
        
        response = requests.post(
            'https://accounts.google.com/_/signup/usernameavailability',
            params=params,
            cookies=cookies,
            headers=headers,
            data=data,
        )
        
        if '"gf.uar",1' in str(response.text):
            return "Available_True"
        else:
            return "Available_False"
        
    except Exception as e:
        print("vpn")
        return False