import streamlit as st
import requests

# Set FastAPI backend URL
API_URL = "https://tharu22-world-population.hf.space"  # Change to your actual FastAPI URL

# Streamlit UI
st.title("🌍 World Population Dashboard")

# Sidebar filter
st.sidebar.header("Filter")
selected_continent = st.sidebar.selectbox(
    "Select a Continent:",
    ["Asia", "Africa", "North America", "South America", "Europe", "Oceania"]
)

if st.sidebar.button("Get Data"):
    # Call FastAPI
    try:
        response = requests.get(f"{API_URL}/{selected_continent}", timeout=10)

        if response.status_code == 200:
            try:
                data = response.json()

                st.header(f"📊 {selected_continent} - Population Statistics")

                # Display data in Streamlit
                st.write(f"🟢 **Max Population:** {data.get('Max', 'N/A')}")
                st.write(f"🔴 **Min Population:** {data.get('Min', 'N/A')}")
                st.write(f"📉 **Average Population:** {data.get('Avgerage', 'N/A')}")
                st.write(f"🌎 **Total Area:** {data.get('Area', 'N/A')}")
                st.write(f"👥 **Total Population:** {data.get('Sum', 'N/A')}")
                st.write(f"🏗 **Population Density:** {data.get('density', 'N/A')}")

            except requests.exceptions.JSONDecodeError:
                st.error(f"Invalid JSON response received:\n{response.text}")

        else:
            st.error(f"API Error {response.status_code}: {response.text}")

    except requests.exceptions.RequestException as e:
        st.error(f"Request failed: {e}")