// ============================================================================
// mesh_validate.cpp — see mesh_validate.h for design notes and the live
// phantom-contact evidence that motivated it.
// ============================================================================

#include "mesh_validate.h"

bool mesh_event_is_plausible(const DetectionEvent& evt) {
    // --- 1. Message type -----------------------------------------------
    // Only these five ride in the 33-byte DetectionEvent layout. This is the
    // single strongest filter: a foreign frame must coincidentally open with
    // one of five specific bytes out of 256.
    switch (evt.msg_type) {
        case MSG_TYPE_DETECTION:
        case MSG_TYPE_CANDIDATE:
        case MSG_TYPE_CORROBORATE:
        case MSG_TYPE_HEALTH:
        case MSG_TYPE_COMPOSITE:
            break;
        default:
            return false;
    }

    // --- 2. Coordinate range -------------------------------------------
    // Catches the impossible latitudes seen live (107.2987782).
    if (evt.lat_fixed >  MESH_LAT_FIXED_MAX) return false;
    if (evt.lat_fixed < -MESH_LAT_FIXED_MAX) return false;
    if (evt.lon_fixed >  MESH_LON_FIXED_MAX) return false;
    if (evt.lon_fixed < -MESH_LON_FIXED_MAX) return false;

    // --- 3. Coordinate zero-consistency --------------------------------
    // Range alone is not enough: the observed phantoms (20.8389635, 0) and
    // (10.0663296, 0) are both technically in-range. What gives them away is a
    // non-zero latitude paired with an exactly-zero longitude — a real fix
    // yields both non-zero, and an absent fix yields both zero. Exactly one
    // being zero means the field was never a coordinate pair to begin with.
    //
    // 0,0 must stay VALID — that is a GPS-less unit honestly reporting "no
    // position" (Spencer03). Only the mixed case is rejected. The residual
    // risk is a genuine sensor on the prime meridian or the equator, which is
    // nowhere near this fleet and is the correct trade at this precision.
    if ((evt.lat_fixed == 0) != (evt.lon_fixed == 0)) return false;

    // --- 4. Battery percentage -----------------------------------------
    if (evt.battery_pct > 100) return false;

    // --- 5. Class label -------------------------------------------------
    if (evt.class_label > CLASS_RID_WIFI_DECODED) return false;

    // --- 6. Flag bits ---------------------------------------------------
    // Only three flag bits are ever set anywhere in the firmware (verified by
    // audit of every assignment to .flags). The upper five bits being clear is
    // another cheap, high-yield structural filter on random data.
    if ((evt.flags & ~MESH_FLAGS_VALID_MASK) != 0) return false;

    // --- 7. RSSI sanity --------------------------------------------------
    if (evt.rssi < MESH_RSSI_MIN_DBM || evt.rssi > MESH_RSSI_MAX_DBM) return false;

    return true;
}
