import type { Perturbation } from '../engine/telemetry'

/**
 * Turn an API scenario overlay into an engine perturbation.
 *
 * The 2.0 analysis routes accept a small overlay so a caller can ask "and what if it
 * were four degrees hotter" without building a full scenario. Keeping the conversion in
 * one place means every route interprets the same overlay identically — a page and an
 * API call with the same body get the same numbers, which is the whole basis for
 * trusting either of them.
 */
export interface AnalysisOverlay {
  loadDeltaPct?: number
  tempDeltaC?: number
  solarDeltaPct?: number
  windDeltaPct?: number
  regionCode?: string | null
}

export function toPerturbation(overlay?: AnalysisOverlay | null): Perturbation | undefined {
  if (!overlay) return undefined
  const perturbation: Perturbation = {}
  if (overlay.loadDeltaPct !== undefined) perturbation.loadDeltaPct = overlay.loadDeltaPct
  if (overlay.tempDeltaC !== undefined) perturbation.tempDeltaC = overlay.tempDeltaC
  if (overlay.solarDeltaPct !== undefined) perturbation.solarDeltaPct = overlay.solarDeltaPct
  if (overlay.windDeltaPct !== undefined) perturbation.windDeltaPct = overlay.windDeltaPct
  if (overlay.regionCode !== undefined) perturbation.regionCode = overlay.regionCode
  return Object.keys(perturbation).length > 0 ? perturbation : undefined
}
