package api import ( "context" "fmt" "log/slog" "net/http" "sort" "time" "pulsecast/api/internal/ml" "pulsecast/api/internal/model" "pulsecast/api/internal/staffing" ) func (s *Server) handleForecast(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() sensor := query.Get("sensor") if sensor == "" { writeError(w, http.StatusBadRequest, "bad_request", "sensor is required") return } if s.cache == nil { writeError(w, http.StatusNotFound, "not_found", "unknown sensor") return } if _, ok := s.cache.Sensor(sensor); !ok { writeError(w, http.StatusNotFound, "not_found", "unknown sensor") return } horizon := query.Get("horizon") if horizon == "" { horizon = "7d" } if !model.Contains(model.Horizons, horizon) { writeError(w, http.StatusBadRequest, "bad_request", "horizon must be one of 15m, 1h, 48h, 7d") return } scenarioName := query.Get("scenario") if scenarioName == "" { scenarioName = "base" } if !model.Contains(model.Scenarios, scenarioName) { writeError(w, http.StatusBadRequest, "bad_request", "unknown scenario") return } state := s.scenario.Get() points, err := s.liveForecast(r.Context(), sensor, horizon, scenarioName, state) cached := false if err != nil { cached = true var ok bool points, ok = s.fallbackForecast(sensor, scenarioName, horizon) if !ok { slog.Warn("forecast unavailable", "sensor", sensor, "horizon", horizon, "scenario", scenarioName, "error", err) writeError(w, http.StatusServiceUnavailable, "forecast_unavailable", "no live forecast and no last good forecast for this sensor, scenario and horizon") return } } else { s.rememberForecast(sensor, horizon, scenarioName, points) } meta := s.meta() s.setVersions(w) writeJSON(w, http.StatusOK, model.ForecastResponse{ Sensor: sensor, Horizon: horizon, Scenario: scenarioName, Points: points, Cached: cached, DataVersion: meta.DataVersion, ModelVersion: meta.ModelVersion, ContextVersion: meta.ContextVersion, }) } func (s *Server) liveForecast(ctx context.Context, sensor, horizon, scenarioName string, state model.ScenarioState) ([]model.ForecastPoint, error) { if s.ml == nil { return nil, fmt.Errorf("ml client not configured") } ctx, cancel := context.WithTimeout(ctx, s.cfg.MLTimeout) defer cancel() ctxData := s.cache.Context() precip := ctxData.Weather.Now.PrecipMM // A zero override means "no scenario rain"; keep the cached current value. if state.Scenario.Weather.PrecipMM > 0 { precip = state.Scenario.Weather.PrecipMM } _, isHoliday := s.holidayOn(state.At) points, err := s.ml.Predict(ctx, ml.PredictRequest{ Sensor: sensor, Horizon: horizon, Scenario: scenarioName, Weather: ml.WeatherInput{ TempC: ctxData.Weather.Now.TempC + state.Scenario.Weather.TempDeltaC, PrecipMM: precip, }, IsHoliday: isHoliday, }) if err != nil { return nil, err } return sortedForecast(points), nil } // fallbackForecast prefers the live /simulate grid for the current scenario, // then the last good /predict response for this exact key. It never labels base // data as another scenario. func (s *Server) fallbackForecast(sensor, scenarioName, horizon string) ([]model.ForecastPoint, bool) { s.mu.RLock() if s.simFor == scenarioName { if horizons, ok := s.sim[sensor]; ok { if points, ok := horizons[horizon]; ok && len(points) > 0 { out := sortedForecast(points) s.mu.RUnlock() return out, true } } } s.mu.RUnlock() return s.lastGoodForecast(sensor, horizon, scenarioName) } func forecastKey(sensor, horizon, scenarioName string) string { return sensor + "|" + horizon + "|" + scenarioName } func (s *Server) rememberForecast(sensor, horizon, scenarioName string, points []model.ForecastPoint) { if len(points) == 0 { return } copied := sortedForecast(points) s.mu.Lock() s.lastForecast[forecastKey(sensor, horizon, scenarioName)] = copied s.mu.Unlock() } func (s *Server) lastGoodForecast(sensor, horizon, scenarioName string) ([]model.ForecastPoint, bool) { s.mu.RLock() points, ok := s.lastForecast[forecastKey(sensor, horizon, scenarioName)] s.mu.RUnlock() if !ok || len(points) == 0 { return nil, false } return sortedForecast(points), true } func sortedForecast(points []model.ForecastPoint) []model.ForecastPoint { out := make([]model.ForecastPoint, len(points)) copy(out, points) sort.Slice(out, func(i, j int) bool { return out[i].T.Before(out[j].T) }) return out } func (s *Server) holidayOn(t time.Time) (string, bool) { if s.cache == nil { return "", false } day := t.In(s.loc).Format("2006-01-02") for _, holiday := range s.cache.Context().Holidays { if holiday.Date == day { return holiday.Name, true } } return "", false } func (s *Server) handleStaffing(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() sensor := query.Get("sensor") if sensor == "" { writeError(w, http.StatusBadRequest, "bad_request", "sensor is required") return } if s.cache == nil { writeError(w, http.StatusNotFound, "not_found", "unknown sensor") return } if _, ok := s.cache.Sensor(sensor); !ok { writeError(w, http.StatusNotFound, "not_found", "unknown sensor") return } scenarioName := query.Get("scenario") if scenarioName == "" { scenarioName = "base" } if !model.Contains(model.Scenarios, scenarioName) { writeError(w, http.StatusBadRequest, "bad_request", "unknown scenario") return } standard := query.Get("standard") if standard == "" { standard = "standard" } if !model.Contains(model.Standards, standard) { writeError(w, http.StatusBadRequest, "bad_request", "standard must be relaxed, standard or premium") return } state := s.scenario.Get() meta := s.meta() s.mu.RLock() generation := s.simGen s.mu.RUnlock() key := fmt.Sprintf("%s|%s|%s|%s|%d|%d", sensor, scenarioName, standard, meta.ContextVersion, state.Version, generation) s.mu.RLock() plan, hit := s.staffing[key] s.mu.RUnlock() if !hit { points, cached, ok := s.staffingForecast(r.Context(), sensor, scenarioName, state) if !ok { writeError(w, http.StatusServiceUnavailable, "staffing_unavailable", "no live or last good 7d forecast for this sensor and scenario") return } built, err := staffing.Build(sensor, scenarioName, standard, points, s.cache.Context()) if err != nil { slog.Warn("staffing build failed", "sensor", sensor, "scenario", scenarioName, "standard", standard, "error", err) writeError(w, http.StatusServiceUnavailable, "staffing_unavailable", "could not build a plan from the available forecast") return } built.Cached = cached s.mu.Lock() s.staffing[key] = built s.mu.Unlock() plan = built } plan.DataVersion = meta.DataVersion plan.ModelVersion = meta.ModelVersion plan.ContextVersion = meta.ContextVersion s.setVersions(w) writeJSON(w, http.StatusOK, plan) } // staffingForecast returns 7d points for a plan. Prefer the scenario simulation // grid, then /predict, and finally the last good forecast. The bool reports // whether the points came from the cache fallback. func (s *Server) staffingForecast(ctx context.Context, sensor, scenarioName string, state model.ScenarioState) ([]model.ForecastPoint, bool, bool) { s.mu.RLock() if s.simFor == scenarioName { if horizons, ok := s.sim[sensor]; ok { if points, ok := horizons["7d"]; ok && len(points) > 0 { out := sortedForecast(points) s.mu.RUnlock() return out, false, true } } } s.mu.RUnlock() points, err := s.liveForecast(ctx, sensor, "7d", scenarioName, state) if err == nil { s.rememberForecast(sensor, "7d", scenarioName, points) return points, false, true } slog.Warn("staffing forecast fallback", "sensor", sensor, "scenario", scenarioName, "error", err) if points, ok := s.lastGoodForecast(sensor, "7d", scenarioName); ok { return points, true, true } return nil, false, false }