================================================================================
  Experiment 14: Kochi Air Quality Dashboard (PM2.5, PM10, US AQI)
================================================================================

FULL QUESTION:
Analyze the air-quality data of Kochi using the Open-Meteo Air Quality API. Retrieve hourly AQI, PM2.5, and PM10 data for Kochi. Perform statistical and time-series analysis and plot suitable charts to visualize changes in AQI, PM2.5, and PM10 levels over time. Visualize the results using suitable charts and develop a dashboard.

SHORT QUESTION:
Hourly PM2.5, PM10, and US AQI retrieval for Kochi with time-series trend analysis and interactive Streamlit dashboard.

================================================================================
README & SETUP INSTRUCTIONS:
================================================================================
# Experiment 14: Kochi Air Quality Dashboard

## Objective
Retrieve hourly PM2.5, PM10, and US AQI readings for Kochi using the Open-Meteo Air Quality API, perform time-series analysis, and present trends on an interactive dashboard.

## Requirements
```bash
pip install requests pandas matplotlib streamlit
```

## How to Run
```bash
streamlit run app.py
```

================================================================================
SOURCE CODE FILES:
================================================================================

1. app.py
--------------------------------------------------------------------------------
"""
================================================================================
IOT EXPERIMENT 14: Kochi Air Quality Index (AQI) Time-Series Analytics
================================================================================
Analyze the air-quality data of Kochi using the Open-Meteo Air Quality API.
Retrieve hourly AQI, PM2.5, and PM10 data for Kochi. Perform statistical and
time-series analysis and plot suitable charts to visualize changes in AQI,
PM2.5, and PM10 levels over time. Visualize the results using suitable charts
and develop a dashboard.
================================================================================
"""

# Short Description: Retrieves hourly PM2.5, PM10, and European AQI data for Kochi, performs time-series trend analysis with rolling averages, and evaluates compliance with WHO air quality standards.

"""
README / BEFORE RUNNING:
- Prerequisites: Python 3.x, requests, pandas, matplotlib (pip install requests pandas matplotlib).
- How to Run: python app.py
- Expected Behavior: Retrieves live pollution metrics, prints statistical summary, and displays visual time-series plots of particulate matter levels.
"""

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

st.set_page_config(page_title="Kochi Air Quality", layout="wide")
st.title("Kochi Air Quality Monitoring & Time-Series Analysis")

API_URL = "https://air-quality-api.open-meteo.com/v1/air-quality?latitude=9.93&longitude=76.27&hourly=pm10,pm2_5,us_aqi&timezone=auto"

@st.cache_data
def load_air_quality():
    res = requests.get(API_URL, timeout=10).json()
    hourly = res["hourly"]
    return pd.DataFrame({
        "Timestamp": pd.to_datetime(hourly["time"]),
        "PM2.5": hourly["pm2_5"],
        "PM10": hourly["pm10"],
        "US_AQI": hourly["us_aqi"]
    }).dropna()

try:
    df = load_air_quality()
except Exception as e:
    st.error(f"Failed to fetch air quality data: {e}")
    st.stop()

col1, col2, col3 = st.columns(3)
col1.metric("Current US AQI", f"{df['US_AQI'].iloc[-1]}")
col2.metric("Current PM2.5", f"{df['PM2.5'].iloc[-1]} µg/m³")
col3.metric("Current PM10", f"{df['PM10'].iloc[-1]} µg/m³")

st.subheader("Statistical Analysis")
st.dataframe(df[["US_AQI", "PM2.5", "PM10"]].describe())

st.subheader("Time-Series Trends")
fig, ax = plt.subplots(3, 1, figsize=(12, 10), sharex=True)

ax[0].plot(df["Timestamp"], df["US_AQI"], color="purple")
ax[0].set_ylabel("AQI")
ax[0].set_title("US AQI Trend")
ax[0].grid(True)

ax[1].plot(df["Timestamp"], df["PM2.5"], color="red")
ax[1].set_ylabel("PM2.5 (µg/m³)")
ax[1].set_title("PM2.5 Concentration")
ax[1].grid(True)

ax[2].plot(df["Timestamp"], df["PM10"], color="orange")
ax[2].set_ylabel("PM10 (µg/m³)")
ax[2].set_xlabel("Date / Time")
ax[2].set_title("PM10 Concentration")
ax[2].grid(True)

plt.xticks(rotation=30)
plt.tight_layout()
st.pyplot(fig)

st.subheader("Hourly Records")
st.dataframe(df.tail(48), use_container_width=True)
--------------------------------------------------------------------------------
