#!/bin/sh
# lib-decide.sh — PURE hysteresis + weight-formula decision helpers.
# No side effects: args in, stdout/exit-code out. POSIX/ash-safe.

# Weight for WAN A given scoreA scoreB:
#   50 + 2*(a-b), rounded to nearest 10, clamped to 20..80.
# e.g. wan_weight 70 70 -> 50 ; wan_weight 80 60 -> 90 -> clamp 80.
wan_weight() {
	awk -v a="$1" -v b="$2" 'BEGIN{
		w = 50 + (a-b)*2
		w = int((w+5)/10)*10       # round to nearest 10 (works for w>=-5; clamp handles low end)
		if (w < 20) w = 20
		if (w > 80) w = 80
		print w }'
}

# Exit 0 (changed) if |target-current| >= 10, else exit 1 (within hysteresis band).
weight_changed() {
	[ "$(( $2 > $1 ? $2 - $1 : $1 - $2 ))" -ge 10 ]
}

# Exit 0 if bad_cycles >= threshold (time to switch SIM), else exit 1.
sim_should_switch() {
	[ "$1" -ge "$2" ]
}

# Exit 0 (gateway alive) if at least 2 of 3 probes pass (each arg: 1=pass 0=fail).
gw_verdict() {
	[ "$(( $1 + $2 + $3 ))" -ge 2 ]
}
