import httpx
import os
from dotenv import load_dotenv

load_dotenv()
API_KEY = os.getenv("GOOGLE_MAPS_API_KEY")
GEOCODE_API_KEY = os.getenv("GOOGLE_GEOCODE_API_KEY")

# Use Text Search (New) which is better for keyword-based lead generation
TEXT_SEARCH_URL = "https://places.googleapis.com/v1/places:searchText"
GEOCODE_URL = "https://maps.googleapis.com/maps/api/geocode/json"

async def get_nearby_businesses(lat: float, lng: float, radius: int, keyword: str, page_token: str = None):
    headers = {
        "Content-Type": "application/json",
        "X-Goog-Api-Key": API_KEY,
        "X-Goog-FieldMask": "places.id,places.displayName,places.formattedAddress,places.nationalPhoneNumber,places.websiteUri,nextPageToken"
    }

    body = {
        "textQuery": keyword,
        "maxResultCount": 20, # Max allowed per page in Text Search (New)
        "locationBias": {
            "circle": {
                "center": {"latitude": lat, "longitude": lng},
                "radius": float(radius)
            }
        }
    }
    
    # If a token is provided, add it to the request
    if page_token:
        import asyncio
        await asyncio.sleep(2)
        body["pageToken"] = page_token

    async with httpx.AsyncClient() as client:
        response = await client.post(TEXT_SEARCH_URL, headers=headers, json=body)
        print(response)
        
        if response.status_code != 200:
            return [], None
            
        data = response.json()
        results = data.get("places", [])
        next_token = data.get("nextPageToken") # Get the token for the next 20 results
        
        final_leads = []
        for place in results:
            final_leads.append({
                "name": place.get("displayName", {}).get("text", "N/A"),
                "phone": place.get("nationalPhoneNumber", "N/A"),
                "website": place.get("websiteUri", "N/A"),
                "address": place.get("formattedAddress", "N/A"),
                "place_id": place.get("id")
            })
        
        return final_leads, next_token

async def get_coordinates_from_google(pincode: int):
    """
    Fallback: Get coordinates for a pincode using Google Geocoding API.
    """
    params = {
        "address": f"pincode {pincode}, India",
        "key": GEOCODE_API_KEY
    }
    
    async with httpx.AsyncClient() as client:
        response = await client.get(GEOCODE_URL, params=params)
        print(f"Google Geocoding response for pincode {pincode}: {response.status_code} response {response}.data {response.json()}")
        if response.status_code == 200:
            data = response.json()
            if data["status"] == "OK":
                location = data["results"][0]["geometry"]["location"]
                return location["lat"], location["lng"]
    
    return None, None
