# scripts/categorias_google.py
from serpapi import GoogleSearch
from dotenv import load_dotenv
from fuzzywuzzy import fuzz
import os

load_dotenv()
API_KEY = os.getenv("SERPAPI_API_KEY")

def obtener_categoria_google(nombre_estab, lat, lon, radio_m=200, umbral_similitud=85, api_key=API_KEY):
    params = {
        "engine": "google_maps",
        "type": "search",
        "q": nombre_estab,
        "ll": f"@{lat},{lon},{radio_m}m",
        "api_key": api_key
    }

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

    try:
        candidatos = results.get("local_results", [])
        for r in candidatos:
            nombre_google = r.get("title", "")
            similitud = fuzz.token_set_ratio(nombre_estab.lower(), nombre_google.lower())
            if similitud >= umbral_similitud:
                tipo_principal = r.get("type", "No disponible")
                tipos = r.get("types", [])
                return tipo_principal, tipos
        return "No encontrado", []
    except Exception as e:
        return "Error", []
