import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt

# 1. Load the cleaned data
df = pd.read_csv('messy_conveyor_data.csv')
df['timestamp'] = pd.to_datetime(df['timestamp'])

# 2. Page Configuration
st.set_page_config(page_title="IIoT Conveyor Monitor", layout="wide")
st.title("🏭 Conveyor Belt Health Monitor")

# 3. Sidebar Filters
st.sidebar.header("Dashboard Settings")
window = st.sidebar.slider("Smoothing Window (Records)", 1, 20, 5)

# 4. Top Row Metrics
latest = df.iloc[-1]
m1, m2, m3 = st.columns(3)
m1.metric("Current Speed", f"{latest['belt_speed_mps']} m/s")
m2.metric("Motor Temp", f"{latest['motor_temp_c']} °C", delta="2.1 °C")
m3.metric("Status", latest['status'], delta_color="inverse")

# 5. Health Visualization
st.subheader("Vibration Analysis (Real-time vs Smoothed)")
df['vibe_smooth'] = df['vibration_rms'].rolling(window=window).mean()

fig, ax = plt.subplots(figsize=(12, 4))
ax.plot(df['timestamp'], df['vibration_rms'], alpha=0.3, label="Raw Noise", color='gray')
ax.plot(df['timestamp'], df['vibe_smooth'], label="Actual Health Trend", color='red', linewidth=2)
ax.axhline(y=3.5, color='orange', linestyle='--', label="Warning Threshold")
ax.legend()
st.pyplot(fig)

# 6. Failure Log
st.subheader("Event Log")
st.dataframe(df[df['status'] != "Normal"].tail(10), use_container_width=True)

