/**
 * Resolve a device's online/offline state, preferring the freshest signal.
 *
 * Precedence: a live stat from THIS run (the probe that just ran) > the
 * persisted reachability verdict written back by a prior probe > the cached
 * `tailscale.online` snapshot. 'unknown' only when nothing at all is known.
 */
export function deviceOnlineState(d, stats) {
    if (stats)
        return stats.reachable ? 'online' : 'offline';
    if (d.reachability)
        return d.reachability.reachable ? 'online' : 'offline';
    if (d.tailscale)
        return d.tailscale.online ? 'online' : 'offline';
    return 'unknown';
}
/** Build the reachability verdict to persist from a fresh probe stat. Pure. */
export function reachabilityFromStats(d, stats) {
    return {
        reachable: stats.reachable,
        via: d.address?.via,
        checkedAt: new Date(stats.fetchedAt).toISOString(),
    };
}
/**
 * Collect the reachability verdicts to write back for a fleet's freshly-read
 * stats map. Only devices present in the registry are included (a stat for a
 * name we don't track is dropped rather than resurrected). Pure — the caller
 * hands the result to {@link writeReachability}.
 */
export function collectReachabilityWriteBacks(reg, statsMap) {
    const out = {};
    for (const [name, stats] of statsMap) {
        const d = reg[name];
        if (!d)
            continue;
        out[name] = reachabilityFromStats(d, stats);
    }
    return out;
}
