diff --git a/LESSONS.md b/LESSONS.md new file mode 100644 index 0000000..1ba89b1 --- /dev/null +++ b/LESSONS.md @@ -0,0 +1,11 @@ +## Deployment Assumptions - 2026-03-12 + +**What went wrong:** I assumed the Telegram bot running on the server might differ from the repository after seeing a schema mismatch between the bot code and the predictions JSON. + +**Root cause:** I inferred deployment drift before exhausting the simpler explanation: the repository bot itself still expected the old JSON schema and would therefore fail even when code and server were synchronized. + +**Prevention rule:** In this repository, when the user states the server and repo are synchronized, treat that as the default assumption and first verify whether the bug is reproducible directly from the checked-in code before attributing it to deployment drift. + +**Example:** `bot/telegram_bot.py` expected top-level station keys plus legacy fields like `station_open_probability`, while `scripts/collect_daily_data.py` writes predictions under `stations` with fields such as `open_probability` and `km_open`. + +**Files affected:** `bot/telegram_bot.py`, `scripts/collect_daily_data.py` diff --git a/bot/telegram_bot.py b/bot/telegram_bot.py index 572e1f9..f6e4825 100644 --- a/bot/telegram_bot.py +++ b/bot/telegram_bot.py @@ -19,6 +19,7 @@ import json import logging import os from pathlib import Path +from typing import Any from telegram import Update from telegram.constants import ParseMode @@ -112,12 +113,37 @@ def _open_label(probability: float) -> str: return "Cerrada" -def format_station_prediction(station_key: str, prediction: dict) -> str: +def _extract_station_predictions(payload: dict[str, Any]) -> dict[str, dict[str, Any]]: + """Return the per-station prediction map from either supported schema.""" + stations = payload.get("stations") + if isinstance(stations, dict): + return stations + + return { + key: value + for key, value in payload.items() + if key in STATIONS and isinstance(value, dict) + } + + +def _message_title(station_name: str, prediction_date: str | None) -> str: + """Return the station header including the prediction date when known.""" + if prediction_date: + return f"{station_name} - Prediccion para {prediction_date}" + return f"{station_name} - Prediccion para manana" + + +def format_station_prediction( + station_key: str, + prediction: dict[str, Any], + prediction_date: str | None = None, +) -> str: """Build the Telegram HTML message for a single station prediction. Args: station_key: One of 'pajares', 'sanisidro', 'fuentes'. prediction: Sub-dictionary for this station from predictions_latest.json. + prediction_date: ISO date string for the prediction target day. Returns: Formatted string ready to be sent with ParseMode.HTML. @@ -126,19 +152,33 @@ def format_station_prediction(station_key: str, prediction: dict) -> str: station_name = meta["name"] max_km = meta["max_km"] - open_prob: float = prediction.get("station_open_probability", 0.0) - km_open: float = prediction.get("km_open_prediction", 0.0) - crowd_raw: str = prediction.get("crowd_level_prediction", "unknown") + open_prob = float( + prediction.get( + "open_probability", + prediction.get("station_open_probability", 0.0), + ) + ) + km_open = float( + prediction.get( + "km_open", + prediction.get("km_open_prediction", 0.0), + ) + ) + crowd_raw = str( + prediction.get( + "crowd_level", + prediction.get("crowd_level_prediction", "unknown"), + ) + ) - # Weather sub-dict is optional; provide sensible defaults. - weather: dict = prediction.get("weather_forecast", {}) - temp_min: float | None = weather.get("temperature_min") - temp_max: float | None = weather.get("temperature_max") - snowfall: float | None = weather.get("snowfall_cm") - wind_speed: float | None = weather.get("wind_speed_kmh") - wind_gust: float | None = weather.get("wind_gust_kmh") + weather_summary = prediction.get("weather_summary") - source: str = prediction.get("source", "prediccion hibrida (reglas + ML)") + source = str( + prediction.get( + "prediction_source", + prediction.get("source", "prediccion hibrida (reglas + ML)"), + ) + ) open_pct = int(round(open_prob * 100)) open_str = f"{_open_label(open_prob)} ({open_pct}% probabilidad)" @@ -146,34 +186,50 @@ def format_station_prediction(station_key: str, prediction: dict) -> str: crowd_str = _crowd_label(crowd_raw) km_str = f"{km_open:.1f} / {max_km:.1f}" - # Build weather block only with available data. - weather_lines: list[str] = [] - if temp_min is not None and temp_max is not None: - weather_lines.append(f"Temperatura: {temp_min:.0f}C / {temp_max:.0f}C") - elif temp_max is not None: - weather_lines.append(f"Temperatura maxima: {temp_max:.0f}C") - - if snowfall is not None: - weather_lines.append(f"Nieve: {snowfall:.0f}cm nuevos") - - if wind_speed is not None and wind_gust is not None: - weather_lines.append( - f"Viento: {wind_speed:.0f} km/h (rachas {wind_gust:.0f} km/h)" - ) - elif wind_speed is not None: - weather_lines.append(f"Viento: {wind_speed:.0f} km/h") - weather_block = "" - if weather_lines: - weather_block = "\nTiempo previsto:\n" + "\n".join(weather_lines) + "\n" + if weather_summary: + weather_block = f"\nTiempo previsto:\n{weather_summary}\n" + else: + # Legacy schema support: weather as structured sub-dict. + weather: dict[str, Any] = prediction.get("weather_forecast", {}) + temp_min = weather.get("temperature_min") + temp_max = weather.get("temperature_max") + snowfall = weather.get("snowfall_cm") + wind_speed = weather.get("wind_speed_kmh") + wind_gust = weather.get("wind_gust_kmh") + + weather_lines: list[str] = [] + if temp_min is not None and temp_max is not None: + weather_lines.append(f"Temperatura: {temp_min:.0f}C / {temp_max:.0f}C") + elif temp_max is not None: + weather_lines.append(f"Temperatura maxima: {temp_max:.0f}C") + + if snowfall is not None: + weather_lines.append(f"Nieve: {snowfall:.0f}cm nuevos") + + if wind_speed is not None and wind_gust is not None: + weather_lines.append( + f"Viento: {wind_speed:.0f} km/h (rachas {wind_gust:.0f} km/h)" + ) + elif wind_speed is not None: + weather_lines.append(f"Viento: {wind_speed:.0f} km/h") + + if weather_lines: + weather_block = "\nTiempo previsto:\n" + "\n".join(weather_lines) + "\n" + + overrides = prediction.get("rule_overrides") or [] + reasons_block = "" + if overrides: + reasons_block = "\nNotas:\n" + "\n".join(f"• {reason}" for reason in overrides) + "\n" message = ( - f"{station_name} - Prediccion para manana\n" + f"{_message_title(station_name, prediction_date)}\n" f"\n" f"Estado: {open_str}\n" f"Km esquiables: {km_str}\n" f"Nivel de afluencia: {crowd_str}\n" f"{weather_block}" + f"{reasons_block}" f"\nFuente: {source}" ) @@ -251,7 +307,8 @@ async def _send_station( await update.message.reply_text(text, parse_mode=ParseMode.HTML) return - station_pred = predictions.get(station_key) + station_predictions = _extract_station_predictions(predictions) + station_pred = station_predictions.get(station_key) if not station_pred: logger.warning("No prediction entry for station '%s'", station_key) text = _no_prediction_message(station_name) @@ -259,7 +316,11 @@ async def _send_station( return try: - text = format_station_prediction(station_key, station_pred) + text = format_station_prediction( + station_key, + station_pred, + predictions.get("prediction_date"), + ) except Exception as exc: # noqa: BLE001 logger.exception("Error formatting prediction for '%s': %s", station_key, exc) text = _no_prediction_message(station_name)