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 _, ok := s.store.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 baked forecast for this sensor, scenario and horizon") return } } s.setVersions(w) writeJSON(w, http.StatusOK, model.ForecastResponse{ Sensor: sensor, Horizon: horizon, Scenario: scenarioName, Points: points, Cached: cached, DataVersion: s.store.Meta().DataVersion, ModelVersion: s.store.Meta().ModelVersion, ContextVersion: s.store.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.store.Context() precip := ctxData.Weather.Now.PrecipMM 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 live /simulate output for the current scenario, then // the baked scenario grid. 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() if points, ok := s.store.Forecast(sensor, scenarioName, horizon); ok { return sortedForecast(points), true } return nil, false } 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) { day := t.In(s.loc).Format("2006-01-02") for _, holiday := range s.store.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 _, ok := s.store.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() points, cached, ok := s.staffingForecast(sensor, scenarioName) if !ok { writeError(w, http.StatusServiceUnavailable, "staffing_unavailable", "no 7d forecast for this sensor and scenario") return } s.mu.RLock() generation := s.simGen s.mu.RUnlock() key := fmt.Sprintf("%s|%s|%s|%d|%d", sensor, scenarioName, standard, state.Version, generation) s.mu.RLock() plan, hit := s.staffing[key] s.mu.RUnlock() if !hit { built, err := staffing.Build(sensor, scenarioName, standard, points, s.store.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 } s.mu.Lock() s.staffing[key] = built s.mu.Unlock() plan = built } plan.Cached = cached plan.DataVersion = s.store.Meta().DataVersion plan.ModelVersion = s.store.Meta().ModelVersion plan.ContextVersion = s.store.Meta().ContextVersion s.setVersions(w) writeJSON(w, http.StatusOK, plan) } // staffingForecast returns the best 7d points and whether they came from the // fallback grid rather than live /simulate output. func (s *Server) staffingForecast(sensor, scenarioName string) ([]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() if points, ok := s.store.Forecast(sensor, scenarioName, "7d"); ok { return sortedForecast(points), scenarioName != "base", true } return nil, false, false }