import os
import re
import time
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException, ElementNotInteractableException


def sanitize_filename(filename):
    return re.sub(r'[\\/*?:"<>|]', '', filename.replace(' ', '_'))


def download_image(url, filepath):
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        with open(filepath, 'wb') as handler:
            handler.write(response.content)
        return True
    except Exception as e:
        print(f"Error downloading {url}: {e}")
        return False


def find_matching_game_image(driver, wait, game_name):
    """Find the image that best matches the game name."""
    try:
        # Wait for search results to load
        time.sleep(3)

        # Get all possible game cards
        possible_selectors = [
            "div[class*='x10l6tqk'] img",
            "a[class*='AppCard'] img",
            "div[class*='AppCard'] img",
            "div[role='main'] img"
        ]

        all_images = []
        for selector in possible_selectors:
            try:
                images = driver.find_elements(By.CSS_SELECTOR, selector)
                all_images.extend(images)
            except:
                continue

        # Look for exact match first
        game_name_clean = game_name.lower().replace('_', ' ')
        for img in all_images:
            try:
                alt_text = img.get_attribute('alt').lower()
                aria_label = img.get_attribute('aria-label').lower() if img.get_attribute('aria-label') else ''

                # Check if the game name appears in either alt text or aria-label
                if game_name_clean in alt_text or game_name_clean in aria_label:
                    return img
            except:
                continue

        # If no exact match found, return the first image (likely the most relevant search result)
        if all_images:
            return all_images[0]

        return None
    except Exception as e:
        print(f"Error finding matching image: {e}")
        return None


def extract_and_download_images(url, game_list, download_path='images'):
    options = webdriver.ChromeOptions()
    options.add_argument("--start-maximized")
    options.add_argument("--disable-notifications")
    options.add_argument("--disable-gpu")
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-dev-shm-usage")

    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=options)
    wait = WebDriverWait(driver, 30)

    if not os.path.exists(download_path):
        os.makedirs(download_path)

    try:
        driver.get(url)
        print("Opening the Meta Quest Store...")
        time.sleep(5)

        for game in game_list:
            try:
                # Find and clear the search box
                search_box_xpath = "//input[@type='text' and contains(@class, 'xjbqb8w')]"
                search_box = wait.until(EC.presence_of_element_located((By.XPATH, search_box_xpath)))
                search_box = wait.until(EC.element_to_be_clickable((By.XPATH, search_box_xpath)))

                # Clear existing search using multiple methods
                search_box.click()
                search_box.clear()
                search_box.send_keys(Keys.CONTROL + "a")  # Select all text
                search_box.send_keys(Keys.DELETE)  # Delete selected text
                time.sleep(1)

                # Enter new search term
                search_box.send_keys(game.replace('_', ' '))
                search_box.send_keys(Keys.RETURN)

                # Find the matching game image
                img_element = find_matching_game_image(driver, wait, game)

                if img_element:
                    img_src = img_element.get_attribute('src')
                    if img_src:
                        img_name = os.path.join(download_path, sanitize_filename(game + '.png'))
                        print(f"Downloading image for {game}...")
                        print(f"Image URL: {img_src}")
                        print(f"Saving to: {img_name}")

                        if download_image(img_src, img_name):
                            print(f"Successfully downloaded image for {game}")
                        else:
                            print(f"Failed to download image for {game}")
                    else:
                        print(f"No image source found for {game}")
                else:
                    print(f"No image element found for {game}")

            except TimeoutException:
                print(f"Timeout waiting for game {game} to load. Skipping...")
            except NoSuchElementException:
                print(f"Game {game} not found. Skipping...")
            except ElementNotInteractableException:
                print(f"Search box not interactable for game {game}. Skipping...")
            except Exception as e:
                print(f"Error processing {game}: {e}")

            # Wait between searches
            time.sleep(2)

    except Exception as e:
        print(f"An unexpected error occurred: {e}")
    finally:
        driver.quit()
        print("Browser closed.")


if __name__ == "__main__":
    url = "https://www.meta.com/en-gb/experiences/section/391914765228253/"

    game_list = [
        "Another_Fisherman's_Tale",
        "Arizona_Sunshine_2",
        "Asgard's_Wrath_2",
        "Assassin's_Creed_Nexus",
        "batman",
        "Beat_Saber",
        "Blacktop_Hoops",
        "Blade_&_Sorcery_Nomad",
        "Breachers",
        "Brink-Traveler",
        "Contractors",
        "Creed_Rise_To_Glory",
        "Demeo",
        "Five_Nights_At_Freddy's_2",
        "Ghost_Giant",
        "GORN",
        "Green_Hell_VR",
        "Expect_You_to_Die_1",
        "l_Expect_You_to_Die_2",
        "In-Death_Unchained",
        "Jurassic_World_Aftermath",
        "Lego",
        "Maskmaker",
        "Meta_Quest_3",
        "Pavlov",
        "Pistol_Whip",
        "Ragna_Rock",
        "Red_Matter_2",
        "Resident_Evil_4",
        "Swarm",
        "Swarm_2",
        "Towers_&_Powers",
        "Townsmen_VR",
        "UNDERDOGS",
        "Until_You_Fall",
        "Vail",
        "Virtual_Desktop",
        "Waltz_of_the_Wizard"
    ]

    extract_and_download_images(url, game_list)


This code is supposed to fdownload the image belonging to the correct element but fails to find the correct image and downloads a wrong file make sure it looks for the correct image

First tell me how i find the correct image file on the website