"""Weather & Climate Analysis (final)

Station : MONTREAL/PIERRE ELLIOTT TRUDEAU INTL A (ECCC station 5415, Climate ID 7025250)
Period  : 2012-01-01 00:00 to 2012-12-31 23:00, hourly, local standard time (8,784 rows, leap year)
Method  : parsed datetimes, phenomenon flags that catch combined labels ("Rain,Fog"),
          explicit operator precedence, means (not sums) of temperature,
          25 km visibility reporting cap flagged, relative input path.
Usage   : python Weather_Climate_Analysis_Final.py Project1-WeatherDataset.csv
"""
import sys
import numpy as np
import pandas as pd

path = sys.argv[1] if len(sys.argv) > 1 else "Project1-WeatherDataset.csv"   # relative path, passed on the command line
df = pd.read_csv(path)
df = df.rename(columns={"Date/Time": "datetime", "Temp_C": "temp_c", "Dew Point Temp_C": "dew_c", "Rel Hum_%": "rh_pct",
                        "Wind Speed_km/h": "wind_kmh", "Visibility_km": "vis_km", "Press_kPa": "press_kpa", "Weather": "weather"})
df["datetime"] = pd.to_datetime(df["datetime"], format="%m/%d/%Y %H:%M")    # parse to real datetimes
df = df.set_index("datetime").sort_index()

# ---------- 1. Quality control ----------
full = pd.date_range(df.index.min(), df.index.max(), freq="h")
qc = {
    "rows": len(df),
    "missing_hours": len(full.difference(df.index)),
    "duplicate_hours": int(df.index.duplicated().sum()),
    "null_values": int(df.isna().sum().sum()),
    "dew_above_temp": int((df.dew_c > df.temp_c).sum()),          # physical check: must be 0
    "share_vis_25km": round((df.vis_km == 25).mean() * 100, 1),    # 25 km is a reporting default, not a measurement
}
print("QC:", qc)

# ---------- 2. Phenomenon flags (match within combined labels) ----------
w = df.weather
flags = {
    "precip": "Rain|Drizzle|Snow|Ice Pellets|Thunder",
    "snow": "Snow|Ice Pellets",
    "rain": "Rain|Drizzle",
    "fog": "Fog",
    "freezing": "Freezing",
    "thunder": "Thunder",
}
for name, pat in flags.items():
    df[name] = w.str.contains(pat, regex=True)
df["clear_family"] = w.isin(["Clear", "Mainly Clear"])
print("Snow: exact label", (w == "Snow").sum(), "| any snow", df.snow.sum())
print("Fog : exact label", (w == "Fog").sum(), "| any fog", df.fog.sum())

# ---------- 3. Condition queries ----------
clear = w == "Clear"
clear_humid_or_visible = clear & ((df.rh_pct > 50) | (df.vis_km > 40))   # Clear AND (RH > 50 OR vis > 40): 1,220 rows
print("Clear hours with RH > 50% or visibility > 40 km:", clear_humid_or_visible.sum())

# Profile by condition: counts and means (temperatures are averaged, never summed)
by_condition = df.groupby("weather").agg(hours=("temp_c", "size"), temp_mean=("temp_c", "mean"),
                                         rh_mean=("rh_pct", "mean"), wind_mean=("wind_kmh", "mean"),
                                         vis_median=("vis_km", "median")).sort_values("hours", ascending=False)
print(by_condition.head(10).round(1))

# ---------- 4. Climate profile ----------
daily = df.resample("D").agg(temp_mean=("temp_c", "mean"), temp_max=("temp_c", "max"), temp_min=("temp_c", "min"),
                             precip_hours=("precip", "sum"))
daily["hdd"] = (18 - daily.temp_mean).clip(lower=0)
daily["cdd"] = (daily.temp_mean - 18).clip(lower=0)
monthly = df.resample("MS").agg(temp_mean=("temp_c", "mean"), rh_mean=("rh_pct", "mean"), wind_mean=("wind_kmh", "mean"),
                                precip_hours=("precip", "sum"), snow_hours=("snow", "sum"), fog_hours=("fog", "sum"))
normals = pd.Series([-9.2, -8.0, -2.0, 6.2, 13.9, 19.0, 21.7, 20.6, 16.0, 8.9, 2.3, -5.0], index=monthly.index)  # 1991-2020
monthly["anomaly_vs_normal"] = monthly.temp_mean - normals
print(monthly.round(2))
indices = {
    "frost_days": int((daily.temp_min < 0).sum()), "ice_days": int((daily.temp_max < 0).sum()),
    "hot_days_30c": int((daily.temp_max >= 30).sum()), "tropical_nights": int((daily.temp_min > 20).sum()),
    "freeze_thaw_days": int(((daily.temp_min < 0) & (daily.temp_max > 0)).sum()),
    "hdd": round(daily.hdd.sum()), "cdd": round(daily.cdd.sum()),
}
print("Climate indices:", indices)

# ---------- 5. Short-term forecast: seasonal/diurnal harmonic baseline + AR residual ----------
t = df.temp_c.to_numpy(); doy = df.index.dayofyear.to_numpy(); hr = df.index.hour.to_numpy()
def design(doy, hr):
    a, b = 2 * np.pi * doy / 366, 2 * np.pi * hr / 24
    return np.column_stack([np.ones_like(a), np.cos(a), np.sin(a), np.cos(2*a), np.sin(2*a), np.cos(b), np.sin(b),
                            np.cos(2*b), np.sin(2*b), np.cos(b)*np.cos(a), np.sin(b)*np.cos(a)])
beta, *_ = np.linalg.lstsq(design(doy, hr), t, rcond=None)
res = t - design(doy, hr) @ beta
lags = [1, 2, 3, 24]
Y = res[24:]; X = np.column_stack([res[24 - p:-p] for p in lags])
phi, *_ = np.linalg.lstsq(X, Y, rcond=None)
hist, fc = list(res[-30:]), []
fdoy = np.array([1 + k // 24 for k in range(72)]); fhr = np.array([k % 24 for k in range(72)])
for _ in range(72):
    v = sum(phi[i] * hist[-p] for i, p in enumerate(lags)); fc.append(v); hist.append(v)
forecast = pd.Series(design(fdoy, fhr) @ beta + np.array(fc), index=pd.date_range("2013-01-01", periods=72, freq="h"))
print("72-h temperature forecast (first 12 h):"); print(forecast.head(12).round(1))

# ---------- 6. Seasonal outlook: annual harmonic, blended with 1991-2020 normals ----------
dd = daily.reset_index(); a = 2 * np.pi * dd.datetime.dt.dayofyear / 365.25
Xh = np.column_stack([np.ones(len(a)), np.cos(a), np.sin(a), np.cos(2*a), np.sin(2*a)])
bh, *_ = np.linalg.lstsq(Xh, dd.temp_mean, rcond=None)
sd = np.std(dd.temp_mean - Xh @ bh, ddof=5)
print("Harmonic coefficients", bh.round(3), "residual sd", round(sd, 2))
print("NOTE: one year from one station supports short-term and seasonal outlooks only, not climate-trend claims.")
