import requests
from .geocode import Geocode
from .utils import haversine_distance
import folium
class Places:

    def __init__(self):
        self.url = "https://overpass-api.de/api/interpreter"
        self.geo = Geocode()


    def nearby(self, place_type, location, radius=1000, details=False):

        coords = self.geo.get_coordinates(location)
        lat = coords["lat"]
        lon = coords["lon"]

        if isinstance(place_type, list):

            filters = "\n".join(
                [f'node["amenity"="{p}"](around:{radius},{lat},{lon});' for p in place_type]
            )
            query = f"""
            [out:json];
            (
            {filters}
            );
            out;
            """
        else:
            query = f"""
            [out:json];
            node["amenity"="{place_type}"](around:{radius},{lat},{lon});
            out;
            """

        response = requests.get(self.url, params={"data": query})
        data = response.json()

        results = []

        for place in data["elements"]:
            name = place.get("tags", {}).get("name")

            if not name:
                continue

            if details:
                results.append({
                    "name": name,
                    "lat": place["lat"],
                    "lon": place["lon"]
                })

            else:
                results.append(name)
        return results


    def nearest(self, place_type, location):

        places = self.nearby(place_type, location, details=True)

        coords = self.geo.get_coordinates(location)

        min_dist = float("inf")
        nearest_place = None

        for p in places:

            d = haversine_distance(
                coords["lat"],
                coords["lon"],
                p["lat"],
                p["lon"]
            )

            if d < min_dist:
                min_dist = d
                nearest_place = p

        return nearest_place
    

    def show_map(self, location, markers=None, zoom=13, filename="map.html"):
        """
        Generate an interactive map centered at the location.
        markers: list of dicts [{'name':'Pizza Hut','lat':31.55,'lon':74.34}]
        """
        coords = self.geo.get_coordinates(location)

        if not coords:
            return None

        m = folium.Map(location=[coords["lat"], coords["lon"]], zoom_start=zoom)

        # Add center marker
        folium.Marker(
            [coords["lat"], coords["lon"]],
            popup=f"Center: {location}",
            icon=folium.Icon(color="red")
        ).add_to(m)

        # Add other markers if provided
        if markers:
            for place in markers:
                folium.Marker(
                    [place["lat"], place["lon"]],
                    popup=place.get("name", ""),
                    icon=folium.Icon(color="blue")
                ).add_to(m)

        # Save map
        m.save(filename)
        print(f"Map saved to {filename}")
