
import requests
import json
import csv
import time
import pandas as pd
from shapely.geometry import shape
from shapely import wkt

names = []
url = "https://nominatim.openstreetmap.org/search"
extra_cols = {"place_id": [], 
              "lat": [], 
              "lon": [], 
              "shelter_bbox": [], 
              "6_min_isochrone": [], 
              "10_min_isochrone": []
              }

with open("clim_shelter.csv", newline="", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    i = 1
    for row in reader:
        valhalla_url = "http://localhost:8002/isochrone"
        place_name = row["name_es"]
        query = f"{place_name}, Bilbao, Spain"
        params = {"q": query, "format": "json", "limit": 1}
        response = requests.get(url, params=params, headers = {"User-Agent": "streamlit-region-app"})
        print (response.json())
        lat = response.json()[0]["lat"] if response.json() else None
        lon = response.json()[0]["lon"] if response.json() else None   
        shelter_bbox = response.json()[0]["boundingbox"] if response.json() else None
        place_id = response.json()[0]["place_id"] if response.json() else None
        print (lat, lon, shelter_bbox, place_id)

        # JSON request for Zubizuri Bridge, Bilbao
        payload = {
            "locations": [
                {
                    "lat": lat,
                    "lon": lon,
                    "name": place_name
                }
            ],
            "costing": "pedestrian",
            "contours": [
                {"time": 6},
                {"time": 10}
            ],
            "polygons": True,
            "denoise": 1, ## We don't want very fine geometry, since we would be keeping this in a STAC
            "generalize": 50 ## We don't want very fine geometry, since we would be keeping this in a STAC
        }

        if lat is not None and lon is not None:
            print (f"Requesting Isochrone for {place_name} at Lat: {lat}, Lon: {lon}")
        else:
            extra_cols["place_id"].append(None)
            extra_cols["lat"].append(None)
            extra_cols["lon"].append(None)
            extra_cols["shelter_bbox"].append(None)
            extra_cols["6_min_isochrone"].append(None)
            extra_cols["10_min_isochrone"].append(None)
            continue

        six_min_isochrone, ten_min_isochrone = None, None
        response = requests.post(valhalla_url, json=payload)
        geojson_data = response.json()

        if response.status_code != 200:
            print (f"Error in Valhalla API Request for {place_name}, Request failed with Status Code: {response.status_code}")
        else: 
            six_min_isochrone, ten_min_isochrone = shape(geojson_data["features"][0]["geometry"]).wkt,  shape(geojson_data["features"][1]["geometry"]).wkt 


        if lat and lon and shelter_bbox:
            extra_cols["place_id"].append(place_id)
            extra_cols["lat"].append(lat)
            extra_cols["lon"].append(lon)
            extra_cols["shelter_bbox"].append(shelter_bbox)
            extra_cols["6_min_isochrone"].append(six_min_isochrone)
            extra_cols["10_min_isochrone"].append(ten_min_isochrone)

        print (f"Processed {i} records")
        print ("-----------------------------")
        i += 1
        time.sleep(2) ## To avoid hitting the rate limit of Nominatim API

df = pd.read_csv("clim_shelter.csv")

# Add new columns
for col_name, values in extra_cols.items():
    df[col_name] = values

# Save
df.to_csv("clim_shelter_enriched.csv", index=False)