#pragma once

#include "fusion_types.h"
#include "threat_cache.h"
#include <vector>

class FusionEngine {
public:
    explicit FusionEngine(ThreatCache& cache, const FusionConfig& cfg);

    // 执行融合, 返回融合后的威胁列表
    std::vector<FusedThreat> fuse(double now, double drone_heading, int image_width = 640);

private:
    // 统一格式: (source, azimuth, confidence, level, index_into_original)
    struct UnifiedEntry {
        std::string source;       // "thermal", "flash", "acoustic"
        double azimuth = 0;
        double confidence = 0;
        FusionThreatLevel level = FusionThreatLevel::SAFE;
        int original_index = 0;   // 用于回查 details
    };

    // 热成像类型 → 单独威胁等级
    static FusionThreatLevel thermal_solo_level(const std::string& type);
    // 声源类型 → 单独威胁等级
    static FusionThreatLevel acoustic_solo_level(const std::string& type);

    // bbox 中心 → 方位角
    double bbox_to_azimuth(int bx, int bw, int image_width, double heading) const;
    // 视线方向 → 方位角
    static double sight_to_azimuth(double sight_x, double heading);

    // 空间关联分组 (不同模态在 15° 内合并)
    std::vector<std::vector<size_t>> spatial_group(
        const std::vector<UnifiedEntry>& entries, double threshold = 15.0) const;

    // 从分组构建 FusedThreat
    FusedThreat build_threat(
        const std::vector<UnifiedEntry>& group_entries,
        const std::vector<ThermalCacheEntry::Detection>& thermal_dets,
        const std::vector<FlashDetection>& flash_items,
        const std::vector<AcousticThreatData>& acoustic_items,
        double now);

    // 威胁升级规则
    FusionThreatLevel escalate(
        const std::vector<UnifiedEntry>& group_entries,
        const std::vector<ThermalCacheEntry::Detection>& thermal_dets,
        const std::vector<AcousticThreatData>& acoustic_items) const;

    // 角度差 (-180, 180]
    static double angle_diff(double a, double b);
    // 加权圆均值
    static double circular_weighted_mean(
        const std::vector<std::pair<double, double>>& azimuths_weights);

    ThreatCache& cache_;
    FusionConfig cfg_;
    int threat_counter_ = 0;
};
