#ifndef THREAT_CORRELATOR_H
#define THREAT_CORRELATOR_H

#include <cstdint>
#include "config.h"
#include "model_manager.h"

// ============================================================================
// Threat Correlator — On-Device Multi-Model Detection Fusion
//
// Receives outputs from all active models each cycle, maintains a rolling
// detection buffer, and correlates across models to identify composite
// threats that no single model could detect alone.
//
// Correlation is rule-based (simple if/else chain), not ML.
// ============================================================================

// Individual detection event in the rolling buffer
struct CorrelatorDetection {
    uint8_t  slot_id;           // which model produced this
    uint8_t  class_label;       // model-specific class label
    float    confidence;
    uint32_t timestamp_ms;      // millis() when detected
    bool     consumed;          // already used in a composite correlation
};

// Composite threat output
struct CompositeThreat {
    CompositeThreatClass threat_class;
    float    combined_confidence;   // geometric mean of constituent confidences
    uint8_t  constituent_count;
    uint8_t  constituent_slots[4];  // up to 4 constituent model slots
    uint8_t  constituent_labels[4]; // their class labels
    float    constituent_confs[4];  // their confidences
    uint32_t timestamp_ms;
    bool     valid;
};

// Initialize the correlator
void correlator_init();

// Feed a single model inference result into the rolling buffer.
// Call this for each valid inference result each cycle.
void correlator_feed(const ModelInferenceResult& result);

// Run the correlation engine over the rolling buffer.
// Returns number of composite threats found this cycle (0 if none).
// Fills threats[] array (caller allocates, max_threats entries).
int correlator_run(CompositeThreat* threats, int max_threats);

// Get the current detection buffer fill level (0..CORRELATOR_BUFFER_SIZE)
uint8_t correlator_buffer_count();

// Reset the correlator (clear rolling buffer)
void correlator_reset();

// Build a DetectionEvent packet from a composite threat for mesh publishing.
// The event uses MSG_TYPE_COMPOSITE and packs the composite class + constituents.
void correlator_build_event(const CompositeThreat& threat,
                            uint32_t sensor_id,
                            DetectionEvent& evt_out);

#endif // THREAT_CORRELATOR_H
