/**
 * Compute Schedule's transient state fields for API + UI.
 * Stays in sync with the spec's `activeState()`:
 *
 *   if !enabled               → 'paused'
 *   else if inflight_count>0  → 'running'
 *   else if last=='failed'    → 'last_failed'
 *   else                      → 'idle'
 *
 * NOT stored — every read recomputes.
 */

import type { DecoratedSchedule, Schedule, ActiveState } from './types';
import { countInflightForSchedule, lastTerminalStatusForSchedule } from './store';

export function computeActiveState(args: {
  enabled: boolean;
  inflight_count: number;
  last_status: string | null;
}): ActiveState {
  if (!args.enabled) return 'paused';
  if (args.inflight_count > 0) return 'running';
  if (args.last_status === 'failed') return 'last_failed';
  return 'idle';
}

export function decorateSchedule(s: Schedule): DecoratedSchedule {
  const inflight_count = countInflightForSchedule(s.id);
  const last_status = lastTerminalStatusForSchedule(s.id);
  const active_state = computeActiveState({
    enabled: s.enabled,
    inflight_count,
    last_status,
  });
  return {
    ...s,
    inflight_count,
    last_status,
    active_state,
  };
}
