
import requests
import json
import os

# Your Google Maps API key
# It's recommended to load this from an environment variable for security
API_KEY = os.environ.get("GOOGLE_MAPS_API_KEY", "YOUR_API_KEY")

def find_stores(latitude, longitude, radius=1000, keyword="store"):
    """
    Finds stores near a given set of coordinates using the Google Maps Places API.

    Args:
        latitude (float): The latitude of the center of the search area.
        longitude (float): The longitude of the center of the search area.
        radius (int, optional): The radius of the search area in meters. Defaults to 1000.
        keyword (str, optional): The keyword to search for (e.g., "grocery", "coffee"). 
                                 Defaults to "store".

    Returns:
        dict: A dictionary containing the API response, or None if an error occurred.
    """
    if API_KEY == "YOUR_API_KEY":
        print("Error: Please set your Google Maps API key in the GOOGLE_MAPS_API_KEY environment variable or directly in the script.")
        return None

    url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json"
    params = {
        "location": f"{latitude},{longitude}",
        "radius": radius,
        "keyword": keyword,
        "key": API_KEY
    }

    try:
        response = requests.get(url, params=params)
        response.raise_for_status()  # Raise an exception for bad status codes
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error fetching data from Google Maps API: {e}")
        return None

if __name__ == "__main__":
    # Example usage:
    # Replace with the coordinates you want to search around
    # For example, the coordinates for the Empire State Building
    example_latitude = 40.7484405
    example_longitude = -73.9856644

    stores_data = find_stores(example_latitude, example_longitude, keyword="coffee")

    if stores_data:
        print("Successfully fetched store data:")
        # Pretty-print the JSON response
        print(json.dumps(stores_data, indent=2))

        # You can then process the results like this:
        for place in stores_data.get("results", []):
            print("-" * 20)
            print(f"Name: {place.get('name')}")
            print(f"Address: {place.get('vicinity')}")
            print(f"Rating: {place.get('rating', 'N/A')}")
            print(f"Open Now: {'Yes' if place.get('opening_hours', {}).get('open_now') else 'No'}")

