from serpapi import GoogleSearch
import datetime  
import pandas as pd

api_key = "e62b6b8d126f5ffea30490592908fde7308ff5e4bf9c64738eb5cea9055a2fcc"

def precio_hoteles(ciudad, api_key,fecha_checkin,fecha_checkout):
    """
    Obtiene todos los precios de hoteles en una ciudad desde Google Hotels usando SerpAPI.
    
    Args:
        ciudad (str): Nombre de la ciudad a buscar.
        api_key (str): API Key de SerpAPI.
    
    Returns:
        pd.DataFrame: Un DataFrame con todos los hoteles encontrados.
    """
    
    #fecha_checkin = datetime.datetime.today().strftime("%Y-%m-%d")
    #fecha_checkout = (datetime.datetime.today() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")

    hoteles_lista = []
    next_page_token = None  # Se inicializa sin token para la primera consulta

    while True:
        params = {
            "engine": "google_hotels",
            "q": f"hoteles en {ciudad}",
            "location": ciudad,
            "check_in_date": fecha_checkin,
            "check_out_date": fecha_checkout,
            "adults": 1,
            "currency": "MXN",
            "api_key": api_key
        }

        if next_page_token:
            params["next_page_token"] = next_page_token  # Se agrega el token si es una consulta siguiente

        search = GoogleSearch(params)
        results = search.get_dict()

        if "properties" not in results:
            print("No se encontraron más hoteles.")
            break  # Se detiene si no hay más datos

        for hotel in results["properties"]:
            hoteles_lista.append({
                "Nombre": hotel.get("name", "No disponible"),
                "Tipo": hotel.get("type", "No disponible"),
                "Tarifa": float(hotel.get("rate_per_night", {}).get("extracted_lowest", 0)),
                "Descuento": hotel.get("deal", "No"),
                "Estrellas": hotel.get("extracted_hotel_class", "No disponible"),
                "Calificación general": hotel.get("overall_rating", "No disponible"),
                "Número reseñas": hotel.get("reviews", "No disponible"),
                "Reseñas 1 estrella": next((r['count'] for r in hotel.get('ratings', []) if r['stars'] == 1), 0),
                "Reseñas 2 estrella": next((r['count'] for r in hotel.get('ratings', []) if r['stars'] == 2), 0),
                "Reseñas 3 estrella": next((r['count'] for r in hotel.get('ratings', []) if r['stars'] == 3), 0),
                "Reseñas 4 estrella": next((r['count'] for r in hotel.get('ratings', []) if r['stars'] == 4), 0),
                "Reseñas 5 estrella": next((r['count'] for r in hotel.get('ratings', []) if r['stars'] == 5), 0),
                "Reseñas ubicación": hotel.get("location_rating", "No disponible"),
                "Check-in": hotel.get("check_in_time", "No disponible"),
                "Check-out": hotel.get("check_out_time", "No disponible"),
                "check_in_date": fecha_checkin,
                "check_out_date": fecha_checkout
            })

        # ✅ Obtener el token para la siguiente página
        next_page_token = results.get('serpapi_pagination', {}).get('next_page_token', None)

        if not next_page_token:
            break  # Si no hay más páginas, se detiene el loop

    # ✅ Unir todos los datos en un solo DataFrame
    df_hoteles = pd.DataFrame(hoteles_lista)

    return df_hoteles  # Retorna el DataFrame con todos los resultados

