#pragma once

#include "fusion_types.h"
#include <mutex>
#include <deque>
#include <vector>
#include <algorithm>

// ── 热成像缓存条目 ──
// 将 thermal_types.h 的 Assessment 简化为融合所需的字段
struct ThermalCacheEntry {
    // 检测结果摘要
    struct Detection {
        std::string type;        // "Person", "Barrel Overheat", etc.
        double confidence = 0;
        double max_temp   = 0;
        int    bbox_x = 0, bbox_y = 0, bbox_w = 0, bbox_h = 0;
    };
    std::vector<Detection> detections;
    double ambient_temp = 0;
    double timestamp    = 0;
};

// ── 线程安全时间窗口缓存 ──
class ThreatCache {
public:
    explicit ThreatCache(double time_window = 0.5)
        : time_window_(time_window) {}

    void add_thermal(const ThermalCacheEntry& entry) {
        std::lock_guard<std::mutex> lk(mutex_);
        thermal_.push_back(entry);
        if (thermal_.size() > kMaxThermal) thermal_.pop_front();
    }

    void add_flash(const FlashDetection& flash) {
        std::lock_guard<std::mutex> lk(mutex_);
        flash_.push_back(flash);
        if (flash_.size() > kMaxFlash) flash_.pop_front();
    }

    void add_acoustic(const AcousticThreatData& threat) {
        std::lock_guard<std::mutex> lk(mutex_);
        acoustic_.push_back(threat);
        if (acoustic_.size() > kMaxAcoustic) acoustic_.pop_front();
    }

    std::vector<ThermalCacheEntry> get_thermal(double now) const {
        std::lock_guard<std::mutex> lk(mutex_);
        std::vector<ThermalCacheEntry> result;
        double cutoff = now - time_window_;
        for (auto& e : thermal_) {
            if (e.timestamp >= cutoff) result.push_back(e);
        }
        return result;
    }

    // 返回时间窗口内最新的一条闪光, 无则返回 false
    bool get_latest_flash(double now, FlashDetection& out) const {
        std::lock_guard<std::mutex> lk(mutex_);
        double cutoff = now - time_window_;
        for (auto it = flash_.rbegin(); it != flash_.rend(); ++it) {
            if (it->timestamp >= cutoff) { out = *it; return true; }
        }
        return false;
    }

    std::vector<AcousticThreatData> get_acoustic(double now) const {
        std::lock_guard<std::mutex> lk(mutex_);
        std::vector<AcousticThreatData> result;
        double cutoff = now - time_window_;
        for (auto& e : acoustic_) {
            if (e.timestamp >= cutoff) result.push_back(e);
        }
        return result;
    }

    void clear() {
        std::lock_guard<std::mutex> lk(mutex_);
        thermal_.clear();
        flash_.clear();
        acoustic_.clear();
    }

private:
    double time_window_;
    mutable std::mutex mutex_;

    static constexpr size_t kMaxThermal  = 20;
    static constexpr size_t kMaxFlash    = 5;
    static constexpr size_t kMaxAcoustic = 20;

    std::deque<ThermalCacheEntry> thermal_;
    std::deque<FlashDetection>    flash_;
    std::deque<AcousticThreatData> acoustic_;
};
