import pandas as pd
import matplotlib.pyplot as plt

# Load the flow data (Orniac & Figeac)
flow_file_path = "débit_Orniac&Figeac.xlsx"
flow_data = pd.read_excel(flow_file_path, parse_dates=["Date et heure"])

# Load the rainfall data
rainfall_file_path = "Q_46_latest-2023-2025_RR-T-Vent.xlsx"
rainfall_data = pd.read_excel(rainfall_file_path, parse_dates=["Date"])

# Resample rainfall data to hourly to match flow data
rainfall_data.set_index("Date", inplace=True)

# Ensure the data overlaps in date ranges
min_date = min(flow_data["Date et heure"].min(), rainfall_data["Date"].min())
max_date = max(flow_data["Date et heure"].max(), rainfall_data["Date"].max())

flow_data = flow_data[(flow_data["Date et heure"] >= min_date) & (flow_data["Date et heure"] <= max_date)]
rainfall_hourly = rainfall_data[(rainfall_data["Date"] >= min_date) & (rainfall_data["Date"] <= max_date)]

# Create the plot
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8), gridspec_kw={"height_ratios": [1, 2]}, sharex=True)

# Rainfall subplot
ax1.bar(
    rainfall_hourly["Date"],
    rainfall_hourly["Rainfall"],
    color="dodgerblue",
    alpha=0.7,
    width=0.02,
    label="Rainfall (mm)"
)
ax1.set_ylabel("Rainfall (mm)", fontsize=12)
ax1.set_ylim(10, 0)  # Reverse y-axis for rainfall
ax1.legend(fontsize=10)
ax1.grid(True, linestyle="--", alpha=0.7)

# Flow subplot
ax2.plot(
    flow_data["Date et heure"],
    flow_data["Valeur à Orniac (en m³/s)"],
    label="Orniac Flow (m³/s)",
    color="orange",
    linewidth=1.5
)
ax2.plot(
    flow_data["Date et heure"],
    flow_data["Valeur à Figeac (en m³/s)"],
    label="Figeac Flow (m³/s)",
    color="blue",
    linewidth=1.5
)
ax2.set_ylabel("Flow (m³/s)", fontsize=12)
ax2.set_xlabel("Date and Time", fontsize=12)
ax2.legend(fontsize=10)
ax2.grid(True, linestyle="--", alpha=0.7)

# Finalize the layout
fig.suptitle("Rainfall and Flow at Figeac and Orniac", fontsize=16)
plt.xticks(rotation=45)
plt.tight_layout(rect=[0, 0, 1, 0.95])

# Show the plot
plt.show()
