import streamlit as st
import pandas as pd
import numpy as np
import plotly.graph_objects as go

# App Configuration
st.set_page_config(page_title="Energy Optimization AI", layout="wide", page_icon="🌞")

# App Title
st.title("🌞⚡ Energy Optimization AI ⚡🌬️")
st.write("""
    Optimize your energy distribution across renewable sources in real-time 
    to maximize efficiency, reduce costs, and promote sustainability.
""")

# Overview Section
st.header("Project Overview")
st.write("""
This application leverages **AI-based decision-making** to analyze your energy usage across solar and wind energy sources. It provides recommendations for optimizing cost-effectiveness and efficiency while maintaining sustainability goals. Use this tool to make informed energy distribution decisions for homes, industries, or renewable energy setups.
""")

# Input Section
st.header("Input Energy Details")
col1, col2 = st.columns(2)

# User Inputs
with col1:
    st.subheader("Solar Energy")
    solar_usage = st.slider("Solar Energy Usage (kWh):", 0.0, 1000.0, 200.0, step=10.0)
    solar_cost = st.slider("Solar Cost per kWh:", 0.0, 10.0, 2.5, step=0.1)

with col2:
    st.subheader("Wind Energy")
    wind_usage = st.slider("Wind Energy Usage (kWh):", 0.0, 1000.0, 300.0, step=10.0)
    wind_cost = st.slider("Wind Cost per kWh:", 0.0, 10.0, 1.8, step=0.1)

# Optimization Logic
if st.button("🚀 Optimize"):
    total_usage = solar_usage + wind_usage

    if total_usage == 0:
        st.error("⚠️ Please enter energy usage for at least one source.")
    else:
        total_cost = (solar_usage * solar_cost) + (wind_usage * wind_cost)
        solar_share = (solar_usage / total_usage) * 100 if solar_usage > 0 else 0
        wind_share = (wind_usage / total_usage) * 100 if wind_usage > 0 else 0

        cost_effective_source = (
            "solar" if solar_cost < wind_cost
            else "wind" if wind_cost < solar_cost
            else "both sources equally"
        )

        suggestion = (
            f"Balance usage between solar and wind energy, prioritizing {cost_effective_source} for lower costs."
        )

        # Display Results
        st.subheader("Optimization Results")
        col3, col4 = st.columns(2)
        with col3:
            st.metric("Total Energy Usage", f"{total_usage:.2f} kWh")
            st.metric("Solar Share", f"{solar_share:.2f}%")
        with col4:
            st.metric("Total Cost", f"{total_cost:.2f} currency")
            st.metric("Wind Share", f"{wind_share:.2f}%")

        st.success(suggestion)

        # Charts
        st.subheader("Visualization")
        chart_data = pd.DataFrame(
            {
                "Energy Source": ["Solar", "Wind"],
                "Usage (kWh)": [solar_usage, wind_usage],
                "Cost (Currency)": [solar_usage * solar_cost, wind_usage * wind_cost],
            }
        )

        # Improved Visualization with Plotly
        fig = go.Figure()

        # Add Usage Bar
        fig.add_trace(go.Bar(
            x=chart_data["Energy Source"],
            y=chart_data["Usage (kWh)"],
            name="Usage (kWh)",
            marker_color='blue'
        ))

        # Add Cost Bar
        fig.add_trace(go.Bar(
            x=chart_data["Energy Source"],
            y=chart_data["Cost (Currency)"],
            name="Cost (Currency)",
            marker_color='green'
        ))

        fig.update_layout(
            barmode='group',
            title="Energy Usage and Cost Comparison",
            xaxis_title="Energy Source",
            yaxis_title="Value",
            legend_title="Metrics",
        )
        st.plotly_chart(fig, use_container_width=True)

        # Explanation
        st.subheader("Detailed Explanation")
        st.write(
            f"Based on your inputs, **{cost_effective_source} energy** is more cost-effective. "
            f"This analysis helps balance your energy sources to minimize costs and maximize efficiency."
        )

# Sidebar
st.sidebar.header("About")
st.sidebar.info("""
This tool helps optimize renewable energy usage for cost savings, sustainability, 
and better energy distribution management.
""")
st.sidebar.header("How It Works")
st.sidebar.write("""
1. **Input Energy Details**: Specify the usage and cost for solar and wind energy.
2. **Optimization**: The tool calculates the total energy usage, cost, and shares of each source.
3. **Visual Analysis**: Get insights into cost-effective strategies with detailed charts and recommendations.
""")