"""REST API endpoints for the SkiPredictor backend.""" from __future__ import annotations import json import logging from datetime import datetime from pathlib import Path from typing import Any import yaml from fastapi import APIRouter, Depends, HTTPException, Query from app.api.auth import get_current_user from app.api.schemas import ( DayForecast, ForecastAllResponse, ForecastHistoryResponse, ForecastHistoryRun, ForecastStationResponse, HealthResponse, StationForecast, StationInfo, StationsResponse, StatusResponse, ) from storage import SQLiteStore logger = logging.getLogger(__name__) router = APIRouter(prefix="/api/v1") _PROJECT_ROOT = Path(__file__).resolve().parents[2] _STATIONS_YAML = _PROJECT_ROOT / "config" / "stations.yaml" # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- _VALID_STATION_IDS: set[str] | None = None def _load_stations_config() -> dict[str, Any]: """Load and cache the stations YAML configuration.""" with open(_STATIONS_YAML) as fh: return yaml.safe_load(fh)["stations"] def _valid_station_ids() -> set[str]: global _VALID_STATION_IDS if _VALID_STATION_IDS is None: _VALID_STATION_IDS = set(_load_stations_config().keys()) return _VALID_STATION_IDS def _open_label(probability: float) -> str: if probability >= 0.70: return "Abierta" if probability >= 0.40: return "Probable apertura" return "Cerrada" def _get_store() -> SQLiteStore: return SQLiteStore() # --------------------------------------------------------------------------- # Endpoints # --------------------------------------------------------------------------- @router.get("/stations", response_model=StationsResponse) def get_stations(user: dict = Depends(get_current_user)) -> StationsResponse: """List all tracked ski stations with metadata.""" cfg = _load_stations_config() stations = [] for sid, data in cfg.items(): stations.append( StationInfo( station_id=sid, name=data["name"], max_km=data["max_km_skiable"], latitude=data["latitude"], longitude=data["longitude"], altitude=data["altitude"], wind_closure_threshold_kmh=data["wind_closure_threshold"], min_snow_depth_cm=data["minimum_snow_depth"], ) ) return StationsResponse(stations=stations) @router.get("/forecast", response_model=ForecastAllResponse) def get_forecast_all(user: dict = Depends(get_current_user)) -> ForecastAllResponse: """Get the latest forecast for all stations.""" store = _get_store() rows = store.load_current_forecasts() return _build_forecast_all(rows) @router.get("/forecast/history", response_model=ForecastHistoryResponse) def get_forecast_history( station_id: str | None = Query(None), date_from: str | None = Query(None), date_to: str | None = Query(None), limit: int = Query(50, ge=1, le=200), offset: int = Query(0, ge=0), user: dict = Depends(get_current_user), ) -> ForecastHistoryResponse: """Get past forecast runs with pagination.""" store = _get_store() total = store.count_past_forecasts( station_id=station_id, date_from=date_from, date_to=date_to ) rows = store.load_past_forecasts( station_id=station_id, date_from=date_from, date_to=date_to, limit=limit, offset=offset, ) runs = [ ForecastHistoryRun( generated_at=r["generated_at"], run_hour=r["run_hour"], prediction_date=r["prediction_date"], station_id=r["station_id"], open_probability=r.get("open_probability"), km_open=r.get("km_open"), crowd_level=r.get("crowd_level"), prediction_source=r.get("prediction_source"), ) for r in rows ] return ForecastHistoryResponse( total=total, limit=limit, offset=offset, runs=runs ) @router.get("/forecast/{station_id}", response_model=ForecastStationResponse) def get_forecast_station(station_id: str, user: dict = Depends(get_current_user)) -> ForecastStationResponse: """Get the latest forecast for a single station.""" valid = _valid_station_ids() if station_id not in valid: raise HTTPException( status_code=404, detail=f"Station '{station_id}' not found. Valid: {', '.join(sorted(valid))}", ) store = _get_store() rows = store.load_current_forecasts(station_id=station_id) cfg = _load_stations_config() generated_at = rows[0]["generated_at"] if rows else None run_hour = rows[0]["run_hour"] if rows else None station_cfg = cfg[station_id] max_km = station_cfg["max_km_skiable"] days = _rows_to_day_forecasts(rows, max_km) return ForecastStationResponse( generated_at=generated_at, run_hour=run_hour, station_id=station_id, name=station_cfg["name"], days=days, ) @router.get("/health", response_model=HealthResponse) def get_health() -> HealthResponse: """Health check endpoint.""" return HealthResponse( status="ok", timestamp=datetime.now().astimezone().isoformat(), ) @router.get("/status", response_model=StatusResponse) def get_status(user: dict = Depends(get_current_user)) -> StatusResponse: """System status: last/next forecast run, training info, bot status.""" from app.main import app_state store = _get_store() # Last forecast run forecasts = store.load_current_forecasts() last_forecast = forecasts[0]["generated_at"] if forecasts else None # Last training run last_training: str | None = None with store.connect() as conn: row = conn.execute( "SELECT completed_at FROM training_runs ORDER BY completed_at DESC LIMIT 1" ).fetchone() if row: last_training = row["completed_at"] # Model info models: dict[str, str] = {} model_dir = _PROJECT_ROOT / "ml" / "models" if model_dir.exists(): for model_file in model_dir.glob("*.joblib"): target = model_file.stem models[target] = target # Database size db_size_mb = 0.0 if store.db_path.exists(): db_size_mb = round(store.db_path.stat().st_size / (1024 * 1024), 1) return StatusResponse( last_forecast_run=last_forecast, next_forecast_run=app_state.get("next_forecast_run"), last_training_run=last_training, next_training_run=app_state.get("next_training_run"), models=models, telegram_bot_active=app_state.get("bot_active", False), stations_count=len(_valid_station_ids()), database_size_mb=db_size_mb, ) # --------------------------------------------------------------------------- # Internal helpers # --------------------------------------------------------------------------- def _rows_to_day_forecasts( rows: list[dict[str, Any]], max_km: float ) -> list[DayForecast]: """Convert raw DB rows into DayForecast models.""" days = [] for r in rows: prob = r.get("open_probability") notes_raw = r.get("rule_notes_json") or "[]" notes = json.loads(notes_raw) if isinstance(notes_raw, str) else notes_raw days.append( DayForecast( date=r["prediction_date"], open_probability=prob, open_label=_open_label(prob) if prob is not None else None, km_open=r.get("km_open"), max_km=max_km, crowd_level=r.get("crowd_level"), weather_summary=r.get("weather_summary"), rule_notes=notes, prediction_source=r.get("prediction_source"), ) ) return days def _build_forecast_all(rows: list[dict[str, Any]]) -> ForecastAllResponse: """Group raw DB rows by station into the all-stations response.""" cfg = _load_stations_config() generated_at = rows[0]["generated_at"] if rows else None run_hour = rows[0]["run_hour"] if rows else None by_station: dict[str, list[dict[str, Any]]] = {} for r in rows: by_station.setdefault(r["station_id"], []).append(r) stations: dict[str, StationForecast] = {} for sid, station_rows in by_station.items(): station_cfg = cfg.get(sid, {}) max_km = station_cfg.get("max_km_skiable", 0.0) stations[sid] = StationForecast( station_id=sid, name=station_cfg.get("name", sid), days=_rows_to_day_forecasts(station_rows, max_km), ) return ForecastAllResponse( generated_at=generated_at, run_hour=run_hour, stations=stations )