import type { IActionConfig, IActionContext, TPowerStatus } from './actions/base-action.ts'; import type { IUpsStatus } from './ups-status.ts'; export interface IUpsActionSource { id: string; name: string; actions?: IActionConfig[]; } export type TUpsTriggerReason = IActionContext['triggerReason']; export type TActionExecutionDecision = | { type: 'suppressed'; message: string } | { type: 'legacyShutdown'; reason: string } | { type: 'skip' } | { type: 'execute'; actions: IActionConfig[]; context: IActionContext }; export function buildUpsActionContext( ups: IUpsActionSource, status: IUpsStatus, previousStatus: IUpsStatus | undefined, triggerReason: TUpsTriggerReason, timestamp: number = Date.now(), ): IActionContext { return { upsId: ups.id, upsName: ups.name, powerStatus: status.powerStatus as TPowerStatus, batteryCapacity: status.batteryCapacity, batteryRuntime: status.batteryRuntime, previousPowerStatus: (previousStatus?.powerStatus || 'unknown') as TPowerStatus, timestamp, triggerReason, }; } export function applyDefaultShutdownDelay( actions: IActionConfig[], defaultDelayMinutes: number, ): IActionConfig[] { return actions.map((action) => { if (action.type !== 'shutdown' || action.shutdownDelay !== undefined) { return action; } return { ...action, shutdownDelay: defaultDelayMinutes, }; }); } export function decideUpsActionExecution( isPaused: boolean, ups: IUpsActionSource, status: IUpsStatus, previousStatus: IUpsStatus | undefined, triggerReason: TUpsTriggerReason, timestamp: number = Date.now(), ): TActionExecutionDecision { if (isPaused) { return { type: 'suppressed', message: `[PAUSED] Actions suppressed for UPS ${ups.name} (trigger: ${triggerReason})`, }; } const actions = ups.actions || []; if (actions.length === 0 && triggerReason === 'thresholdViolation') { return { type: 'legacyShutdown', reason: `UPS "${ups.name}" battery or runtime below threshold`, }; } if (actions.length === 0) { return { type: 'skip' }; } return { type: 'execute', actions, context: buildUpsActionContext(ups, status, previousStatus, triggerReason, timestamp), }; }