"""SerpApi wrapper for Google Shopping searches and product details.""" from serpapi import GoogleSearch from config import SERPAPI_KEY, DEFAULT_NUM_RESULTS def search_shopping(query, num_results=DEFAULT_NUM_RESULTS, **filters): """ Search Google Shopping via SerpApi. Note: Price filters are NOT sent to SerpApi because its price filtering can be inconsistent. Instead, we fetch a broad set of results and filter them client-side in product_parser.apply_filters() for more reliable price-based filtering. Args: query: Search keywords num_results: Number of results to return **filters: Additional filters (ignored for now; kept for API compatibility) Returns: dict: Raw SerpApi response """ params = { "engine": "google_shopping", "q": query, "api_key": SERPAPI_KEY, "num": num_results, } # NOTE: We intentionally do NOT pass min_price/max_price to SerpApi. # SerpApi's price filtering is unreliable and limits the result set. # Client-side filtering (in apply_filters) gives us more control. try: results = GoogleSearch(params).get_dict() # Debug: print result count num_results = len(results.get("shopping_results", [])) print(f"SerpApi returned {num_results} results for query: {query}") return results except Exception as e: print(f"Error searching: {e}") import traceback traceback.print_exc() return {"shopping_results": []} def get_product_details(immersive_token): """ Fetch detailed product information via SerpApi Immersive Product API. Args: immersive_token: immersive_product_page_token from shopping search results Returns: dict: Product details including description and features """ if not immersive_token: return {} params = { "engine": "google_immersive_product", "page_token": immersive_token, "api_key": SERPAPI_KEY, } try: result = GoogleSearch(params).get_dict() product_results = result.get("product_results", {}) about = product_results.get("about_the_product", {}) # Extract description and features description = about.get("description", "") features = about.get("features", []) # Convert features list to a dict for easier access features_dict = {} for feature in features: title = feature.get("title", "") value = feature.get("value", "") if title and value: features_dict[title] = value return { "description": description, "specs": features_dict } except Exception as e: print(f"Error fetching product details: {e}") import traceback traceback.print_exc() return {}