# Python 14 (streamlit, API)

# Python 14 (streamlit, API)
Photo by Waldemar Brandt / Unsplash
import requests
import pandas as pd
import streamlit as st
import folium
from streamlit_folium import st_folium

st.set_page_config(layout="wide")

st.title("🌍 Aplikacja pogodowa")

def pobierz_pogode(lat: str, lon: str) -> dict:
    url = "https://api.open-meteo.com/v1/forecast"
    querystring = {
        "latitude": lat,
        "longitude": lon,
        "past_days": "20",
        "hourly": "temperature_2m,relative_humidity_2m,wind_speed_10m"
    }
    response = requests.get(url, params=querystring)
    return response.json()

# Sekcja z mapą i współrzędnymi geo i info, że trzeba kliknąć
st.header("Wybierz lokalizację na mapie")

col1, col2 = st.columns([2, 1])

with col1:
    m = folium.Map(location=[39.949610, -75.150282], zoom_start=2)
    mapka = st_folium(m, width=725, height=500)

with col2:
    if mapka and mapka.get("last_clicked"):
        lat = mapka["last_clicked"]["lat"]
        lon = mapka["last_clicked"]["lng"]
        st.subheader("Położenie geograficzne")
        st.metric("Szerokość geograficzna", f"{lat:.4f}°")
        st.metric("Długość geograficzna", f"{lon:.4f}°")
    else:
        st.info("👆 Kliknij na mapę, aby wybrać lokalizację")

# Sekcja z danymi pogodowymi
if mapka and mapka.get("last_clicked"):
    lat = mapka["last_clicked"]["lat"]
    lon = mapka["last_clicked"]["lng"]
    
    with st.spinner('Pobieranie danych pogodowych...'):
        pogoda = pobierz_pogode(f"{lat:.2f}", f"{lon:.2f}")
    
    pogoda_df = pd.DataFrame(pogoda["hourly"])
    jednostki = pogoda["hourly_units"]
    
    st.divider()
    
    # Wykresik
    st.header("📊 Wykres danych pogodowych")
    st.line_chart(pogoda_df.set_index("time"), height=400)
    
    st.divider()
    
    # Dane pogodowe i jednostki w tabelkach
    col3, col4 = st.columns([3, 1])
    
    with col3:
        st.subheader("Dane pogodowe")
        st.dataframe(pogoda_df, height=400, use_container_width=True)
    
    with col4:
        st.subheader("Jednostki")
        jednostki_df = pd.DataFrame(list(jednostki.items()), columns=['Parametr', 'Jednostka'])
        st.dataframe(jednostki_df, hide_index=True, use_container_width=True)