// Campaign time-scale helpers — the single口径 for turning a service-cycle
// window + a desired "how long it should actually take" into the backend's raw
// time_scale, and back again for display. The API contract stays in time_scale;
// users only ever think in durations.
//
// Relation: time_scale = window_seconds ÷ accelerated_seconds. So a 24h window
// that should finish in 1h runs at ×24; real wall-clock (time_scale 1) finishes
// in exactly the window length.

/** Derive the raw time_scale from a window and the desired accelerated runtime. */
export function deriveTimeScale(windowSeconds: number, targetSeconds: number): number {
  if (targetSeconds <= 0) return 1
  return windowSeconds / targetSeconds
}

/** "×N" display for a raw time_scale. */
export function formatScale(timeScale: number): string {
  return `×${trim(timeScale)}`
}

/** Seconds the campaign actually takes once accelerated by time_scale. */
function acceleratedSeconds(windowSeconds: number, timeScale: number): number {
  if (timeScale <= 0) return windowSeconds
  return windowSeconds / timeScale
}

/** Human "约 X" duration, rounded to the coarsest sensible unit. */
function formatDuration(seconds: number): string {
  if (!Number.isFinite(seconds) || seconds <= 0) return '—'
  if (seconds < 60) return `${Math.round(seconds)} 秒`
  const mins = seconds / 60
  if (mins < 60) return `${trim(mins)} 分钟`
  const hours = mins / 60
  if (hours < 48) return `${trim(hours)} 小时`
  return `${trim(hours / 24)} 天`
}

/** Display string for list/detail: "约 X 完成", derived from window + time_scale. */
export function acceleratedDuration(windowSeconds: number, timeScale: number): string {
  if (timeScale === 1) return '实时'
  return `约 ${formatDuration(acceleratedSeconds(windowSeconds, timeScale))}完成`
}

function trim(n: number): string {
  return Number.isInteger(n) ? String(n) : n.toFixed(1)
}
