from bs4 import BeautifulSoup
import requests
import json

def findPost(filePath = 'test.json'):
    params = {'av': '17841401225494803','__a': '1','__req': '1','__hs': '19906.HYP:instagram_web_pkg.2.1..0.1','dpr': '1','__ccg': 'UNKNOWN','__rev': '1014609539','__s': 'guk60j:651i2v:pmhu0r','__hsi': '7386834689999716220','__dyn': '7xe5WwlEnwn8K2Wmm1twpUnwgU7S6EdF8aUco38w5ux609vCwjE1xoswaq0yE6u0nS4oaEd86a3a1YwBgao1aU2swbOU2zxe2GewGw9a362W2K0zEnwhEe82mwww4cwJCwLyES1TwTwFwIwbS1LwTwKG1pg2Xwr86C1mwrd6goK3ibxKi2K7ErwYCz8rwHw','__csr': 'igAzIj5OgR5YBHdRtivbkyFv-zJIZE_ykzfahdAydeHCHAAAqyk4pqBgDzeV4-qlbBF29UlCxFpVokDwAyosyV9KWUmx6iu58WqdwSDCDAFwHxi3C00lWy2FG4k583NxW8yFE0bUyxd06lxO5C2a8yFm2u290ejg1JU2Gw2rQ061U','__comet_req': '7','fb_dtsg': 'NAcPDfX2XufdLkctek6zNxz3DWxPW4t-cJzz39QtOQ5KS-_Rq3erT4A:17843708194158284:1719013044','jazoest': '26262','lsd': 'D0zmaX16yIQu_GwDXKTbMc','__spin_r': '1014609539','__spin_b': 'trunk','__spin_t': '1719881474','__jssesw': '1','fb_api_caller_class': 'RelayModern','fb_api_req_friendly_name': 'PolarisProfilePageContentDirectQuery', 'variables': '{"id":"57771591453","render_surface":"PROFILE"}','server_timestamps': 'true','doc_id': '7663723823674585'}
    
    data = requests.get('https://www.instagram.com/graphql/query')

    posts = data['data']['xdt_api__v1__feed__user_timeline_graphql_connection']['edges']
    posts = [post['node'] for post in posts]

    return max(posts, key=lambda post: max(c['width'] * c['height'] for c in post['image_versions2']['candidates']))

def getHDProfilePicture():
    url = 'https://www.save-free.com/process'

    zoom_data = {'instagram_url': 'natahalieeee','type': 'profile','resource': 'zoom'}
    data = {'instagram_url': 'natahalieeee','type': 'profile','resource': 'save'}

    headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36','Referer' : 'https://www.save-free.com/profile-downloader/',}

    response = requests.post(url, data=data, headers=headers)

    response = requests.post(url, data=zoom_data, headers=headers)

    with open('image.jpg', 'wb') as f:
        f.write(response.content)
        

def get_username_by_user_id(user_id):
    url = 'https://www.instagram.com/graphql/query/'
    
    variables = {
        "user_id": str(user_id),
        "include_chaining": False,
        "include_reel": True,
        "include_suggested_users": False,
        "include_logged_out_extras": False,
        "include_highlight_reels": False,
        "include_related_profiles": False
    }
    
    params = {
        'query_hash': 'c9100bf9110dd6361671f113dd02e7d6',
        'variables': json.dumps(variables)
    }
    
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
    }
    
    response = requests.get(url, headers=headers, params=params)
    
    if response.status_code == 200:
        try:
            data = response.json()
            username = data['data']['user']['reel']['user']['username']
            return username
        except (KeyError, TypeError) as e:
            print(f"Error parsing JSON response: {e}")
            return None
    else:
        print(f"Failed to fetch data. Status code: {response.status_code}")
        return None

def extract_script_tags(username):
    url = f"https://www.instagram.com/{username}/"
    try:
        # Fetch the HTML content of the page
        response = requests.get(url)
        response.raise_for_status()
        
        # Parse the HTML content with BeautifulSoup
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # Find the specific script tag by its type
        scripts = soup.find_all('script', {'type': 'application/json'})
        
        if scripts:
            return scripts
        else:
            return False
    except requests.exceptions.RequestException as e:
        return f"Error fetching the URL: {e}"

def find_item_in_json(json_data, key):
    """
    Recursively searches for the first occurrence of a key in a JSON-like structure (dict or list).

    :param json_data: JSON data (dict or list) to search.
    :param key: The key to find.
    :return: The value of the first occurrence of the key, or None if not found.
    """
    if isinstance(json_data, dict):
        for k, v in json_data.items():
            if k == key:
                return v
            elif isinstance(v, (dict, list)):
                result = find_item_in_json(v, key)
                if result is not None:
                    return result
    elif isinstance(json_data, list):
        for item in json_data:
            if isinstance(item, (dict, list)):
                result = find_item_in_json(item, key)
                if result is not None:
                    return result
    return None  # Return None if the key is not found

def get_user_id(username):
    """
    Extracts the user ID (profile_id) from JSON data embedded in script tags for a given username.

    :param username: The username to process.
    :return: The user ID (profile_id) if found, otherwise None.
    """
    scripts = extract_script_tags(username)  # Replace this with your implementation
    for script in scripts:
        if "profile_id" in str(script):
            try:
                json_data = json.loads(script.string)  # Parse JSON from the script
                user_id = find_item_in_json(json_data, 'profile_id')  # Search for 'profile_id'
                if user_id:
                    return user_id
            except (json.JSONDecodeError, AttributeError):
                # Handle JSON decoding errors or missing script content
                continue
    return None  # Return None if no 'profile_id' is found

def get_profile_data(username):
    url = 'https://www.instagram.com/graphql/query'

    data = {
        'av': '17841401225494803',
        '__d': 'www',
        '__user': 0,
        '__a': 1,   
        '__req': 2,
        '__hs': '20047.HYP:instagram_web_pkg.2.1..0.1',
        'dpr': 1,
        '__ccg': 'EXCELLENT',
        '__rev': 1018347086,
        '__s': '8di41h:vwko3r:whjifd',
        '__hsi': 7439320945163371549,
        '__dyn': '7xe5WwlEnwn8K2Wmm1twpUnwgU7S6EdF8aUco38w5ux60p-0LVE4W0qa0FE2awgo1EUhwnU6a3a0EA2C0iK0D830wae4UaEW2G0AEco5G0zE5W0Y81eEdEGdwtU662O0Lo6-3u2WE15E6O1FwlE6PhA6bwg8rAwHxW1oCz8rwHwcOEym5oqw',
        '__csr': 'hA5I8EAy7hnfqiIBklLZHVkmTHQmVmAh5UCchA9GQByu_yfD-nUBaVaDmSbDyUydCDgzyQAcggDK48Sm2ai8y8lxe6UTgmjwCyUC8yFXK9zooxmez9FUW684qu4awQwF9w04XAg0wi0nB03981oU082Oa0fMe3e19g512AK6Ulo5C3lw7Uy8G6Efo9k08mgiaaw25VobU2bw3KU023zw6Pw',
        '__comet_req': 7,
        'fb_dtsg': 'NAcO7gvrsNlfWXA8giwQC4bVYRXXAGomAqcIRYUJUE2Hk8HmABf56Yg:17854575481098892:1732030177',
        'jazoest': 26190,
        'lsd': 'zcsn3c8we8kpMB_AVukeii',
        '__spin_r': 1018347086,
        '__spin_b': 'trunk',
        '__spin_t': 1732101883,
        'fb_api_caller_class': 'RelayModern',
        'fb_api_req_friendly_name': 'PolarisProfilePageContentQuery',
        'variables': '{"id":"6687693830","render_surface":"PROFILE"}',
        'server_timestamps': 'true',
        'doc_id': 9539110062771438
    }

    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
    }


    response = requests.post(url, headers=headers, data=data)

    json_data = response.json()

    return json_data


username_check = 'tal_ohana'

user_id = get_user_id(username_check)

username = get_username_by_user_id(user_id)

if username:
    print(f"Username: {username}")
else:
    print("Could not retrieve username.")