"""FastAPI application for the SkiPredictor backend. Manages: - REST API serving forecast data - APScheduler for periodic forecast generation and retraining - Telegram bot (in-process, no subprocess) """ from __future__ import annotations import logging import os from contextlib import asynccontextmanager from datetime import datetime from pathlib import Path from typing import Any, AsyncIterator from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.triggers.cron import CronTrigger from fastapi import FastAPI from app.api.auth import auth_router from app.api.routes import router from app.scheduler.tasks import run_extended_task, run_standard_task, run_training_task logger = logging.getLogger(__name__) _PROJECT_ROOT = Path(__file__).resolve().parents[1] _TIMEZONE = "Europe/Madrid" # Shared mutable state visible to the /status endpoint app_state: dict[str, Any] = { "bot_active": False, "next_forecast_run": None, "next_training_run": None, } # --------------------------------------------------------------------------- # Lifespan # --------------------------------------------------------------------------- def _start_scheduler() -> BackgroundScheduler: """Configure and start the APScheduler instance.""" scheduler = BackgroundScheduler(timezone=_TIMEZONE) # Standard forecast: 5:00, 10:00, 15:00 scheduler.add_job( run_standard_task, trigger=CronTrigger(hour="5,10,15", minute=0, timezone=_TIMEZONE), id="forecast_standard", name="Standard forecast run", replace_existing=True, ) # Extended forecast: 20:00 scheduler.add_job( run_extended_task, trigger=CronTrigger(hour=20, minute=0, timezone=_TIMEZONE), id="forecast_extended", name="Extended forecast run (20:00)", replace_existing=True, ) # Training: Sunday 21:00 scheduler.add_job( run_training_task, trigger=CronTrigger(day_of_week="sun", hour=21, minute=0, timezone=_TIMEZONE), id="retrain_weekly", name="Weekly model retrain (Sunday 21:00)", replace_existing=True, ) scheduler.start() logger.info("APScheduler started with %d jobs.", len(scheduler.get_jobs())) # Populate next-run info for /status _update_next_runs(scheduler) return scheduler def _update_next_runs(scheduler: BackgroundScheduler) -> None: """Refresh next_forecast_run and next_training_run in app_state.""" forecast_next: datetime | None = None training_next: datetime | None = None for job in scheduler.get_jobs(): nrt = job.next_run_time if nrt is None: continue if job.id.startswith("forecast_"): if forecast_next is None or nrt < forecast_next: forecast_next = nrt elif job.id == "retrain_weekly": training_next = nrt app_state["next_forecast_run"] = ( forecast_next.isoformat() if forecast_next else None ) app_state["next_training_run"] = ( training_next.isoformat() if training_next else None ) async def _start_bot() -> Any: """Start the Telegram bot in-process. Returns the Application or None.""" token = os.environ.get("TELEGRAM_BOT_TOKEN") if not token: logger.warning( "TELEGRAM_BOT_TOKEN not set. Telegram bot will NOT start." ) return None from bot.telegram_bot import create_bot_application try: bot_app = create_bot_application(token) await bot_app.initialize() await bot_app.start() await bot_app.updater.start_polling() app_state["bot_active"] = True logger.info("Telegram bot started in-process.") return bot_app except Exception as exc: logger.error("Failed to start Telegram bot: %s", exc) return None async def _stop_bot(bot_app: Any) -> None: """Gracefully stop the in-process Telegram bot.""" if bot_app is None: return app_state["bot_active"] = False try: await bot_app.updater.stop() await bot_app.stop() await bot_app.shutdown() logger.info("Telegram bot stopped.") except Exception as exc: logger.error("Error stopping Telegram bot: %s", exc) @asynccontextmanager async def lifespan(application: FastAPI) -> AsyncIterator[None]: """Manage startup and shutdown of scheduler and bot.""" scheduler = _start_scheduler() bot_app = await _start_bot() yield logger.info("Shutting down scheduler and bot...") scheduler.shutdown(wait=False) await _stop_bot(bot_app) # --------------------------------------------------------------------------- # App # --------------------------------------------------------------------------- _DESCRIPTION = """\ Forecast API for ski stations in northern Spain. ## Authentication All endpoints except `/health` require a valid JWT bearer token. Register a user and login to obtain one (valid for 14 days). ## Endpoints | Method | Path | Auth | Description | |--------|------|------|-------------| | POST | `/api/v1/auth/register` | No | Create user account | | POST | `/api/v1/auth/login` | No | Obtain JWT (14 days) | | GET | `/api/v1/health` | No | Health check | | GET | `/api/v1/stations` | **Yes** | List tracked stations | | GET | `/api/v1/forecast` | **Yes** | Latest forecast (all stations) | | GET | `/api/v1/forecast/history` | **Yes** | Past forecast runs | | GET | `/api/v1/forecast/{station_id}` | **Yes** | Forecast for one station | | GET | `/api/v1/status` | **Yes** | System status | """ app = FastAPI( title="SkiPredictor API", version="1.0.0", description=_DESCRIPTION, lifespan=lifespan, ) app.include_router(router) app.include_router(auth_router)