import streamlit as st
import pandas as pd
import os
import plotly.express as px
# π Set the correct data folder path
DATA_FOLDER = "data/"
# π οΈ Function to load CSV files dynamically
@st.cache_data
def load_data(folder):
    data_dict = {}
    
    for file in os.listdir(folder):
        if file.endswith(".csv"):
            file_path = os.path.join(folder, file)
            place_name = file.replace("chadjasmean_data.csv", "").replace(".csv", "").replace("_", " ").strip()
            df = pd.read_csv(file_path, header=None)  # Load CSV without column names
            
            # π’ Rename columns correctly
            df.columns = ["Year", "Rainfall"]
            # π’ Convert "Year" values: 1 β 1991, ..., 35 β 2025
            df["Year"] = pd.to_numeric(df["Year"], errors="coerce")  # Convert safely
            df.dropna(subset=["Year"], inplace=True)  # Remove invalid values
            df["Year"] = df["Year"].astype(int) + 1990  # Shift to correct years
            # π’ Ensure Rainfall values are numeric
            df["Rainfall"] = pd.to_numeric(df["Rainfall"], errors="coerce")
            data_dict[place_name] = df  # Store cleaned data
    return data_dict
# π Load datasets dynamically
data_dict = load_data(DATA_FOLDER)
# π¨ Streamlit UI
st.title("π Rainfall Hindcast Interactive Dashboard")
st.write("Select a region to visualize rainfall trends:")
# π½ Dropdown for region selection
region = st.selectbox("Select Region", list(data_dict.keys()))
# π Plot the data using Plotly
if region:
    df = data_dict[region]
    # π Create a Plotly line chart
    fig = px.line(df, x="Year", y="Rainfall", markers=True, 
                  title=f"Rainfall Trends for {region}")
    # π Customize the layout
    fig.update_layout(
        xaxis_title="Year",
        yaxis_title="Rainfall (mm)",
        hovermode="x",
        template="plotly_white"
    )
    # πΌοΈ Show the interactive chart
    st.plotly_chart(fig, use_container_width=True)