#pragmaonce
#include <vector>
#include <atomic>
#include <chrono>
#include <functional>
#include <opencv2/opencv.hpp>
#include <opencv2/cudaarithm.hpp>
#include <opencv2/cudabgsegm.hpp>

namespace ExtremeTracker {

// 追踪结果结构
struct TrackingResult {
    cv::Rect2f bbox;
    float confidence;
    cv::Point2f velocity;
    cv::Point2f acceleration;
    int track_id;
    uint64_t frame_id;
    double timestamp;
    std::vector<cv::Point2f> trajectory;
};

// 高性能配置
struct TrackerConfig {
    int max_fps = 480;
    int trajectory_buffer_size = 60;
    float min_confidence = 0.98f;
    float max_acceleration = 1000.0f;
    bool use_gpu = true;
    bool enable_prediction = true;
};

// 核心追踪函数库
class ExtremeTrackingEngine {
public:
    // 初始化追踪引擎
    static bool EXTRACT_TRK_Initialize(const TrackerConfig& config = TrackerConfig());
    
    // 主追踪函数 - 单帧处理
    static std::vector<TrackingResult> EXTRACT_TRK_ProcessFrame(
        const cv::Mat& frame, 
        uint64_t frame_id = 0);
    
    // GPU加速版本
    static std::vector<TrackingResult> EXTRACT_TRK_ProcessFrameGPU(
        const cv::cuda::GpuMat& frame, 
        uint64_t frame_id = 0);
    
    // 多目标追踪入口
    static std::vector<TrackingResult> EXTRACT_TRK_TrackMultiple(
        const cv::Mat& frame,
        const std::vector<cv::Rect>& init_bboxes,
        uint64_t frame_id = 0);
    
    // 高级预测函数
    static cv::Point2f EXTRACT_TRK_PredictPosition(
        const std::vector<cv::Point2f>& trajectory,
        const std::vector<double>& timestamps,
        float predict_time = 0.1f);
    
    // 轨迹分析函数
    static void EXTRACT_TRK_AnalyzeTrajectory(
        const std::vector<cv::Point2f>& trajectory,
        cv::Point2f& velocity,
        cv::Point2f& acceleration,
        float& stability);
    
    // 性能监控函数
    static void EXTRACT_TRK_GetPerformanceStats(
        double& current_fps, 
        double& processing_time, 
        int& active_tracks);

    // 清理资源
    static void EXTRACT_TRK_Cleanup();
};

// ==================== 核心算法实现 ====================

class TrackingCore {
private:
    static std::atomic<bool> s_initialized;
    static TrackerConfig s_config;
    static cv::Ptr<cv::cuda::FarnebackOpticalFlow> s_optical_flow;
    static std::vector<TrackedObject> s_active_tracks;
    static HighPrecisionClock s_perf_clock;
    static uint64_t s_frame_counter;
    
    struct TrackedObject {
        int id;
        std::vector<cv::Point2f> positions;
        std::vector<double> timestamps;
        cv::Point2f kalman_velocity;
        cv::Point2f kalman_acceleration;
        cv::KalmanFilter kf;
        int age;
        int hits;
        int misses;
        bool is_confirmed;
    };
    
public:
    // 初始化实现
    static bool initializeImpl(const TrackerConfig& config) {
        if (s_initialized) return true;
        
        s_config = config;
        
        if (s_config.use_gpu) {
            s_optical_flow = cv::cuda::FarnebackOpticalFlow::create(
                5, 0.5, false, 20, 7, 7, 1.5, 0);
        }
        
        s_initialized = true;
        return true;
    }
    
    // 核心追踪算法
    static std::vector<TrackingResult> trackFrameImpl(const cv::Mat& frame, uint64_t frame_id) {
        auto start_time = std::chrono::high_resolution_clock::now();
        
        std::vector<TrackingResult> results;
        
        // 步骤1: 运动检测
        auto motion_targets = detectMotionTargets(frame);
        
        // 步骤2: 特征提取
        auto features = extractAdvancedFeatures(frame, motion_targets);
        
        // 步骤3: 轨迹关联
        associateWithTracks(features, frame_id);
        
        // 步骤4: 预测更新
        updateTrackPredictions();
        
        // 步骤5: 生成结果
        results = generateTrackingResults();
        
        auto end_time = std::chrono::high_resolution_clock::now();
        auto duration = std::chrono::duration<double>(end_time - start_time).count();
        
        // 帧率控制
        double target_time = 1.0 / s_config.max_fps;
        if (duration < target_time) {
            std::this_thread::sleep_for(
                std::chrono::microseconds(static_cast<int>((target_time - duration) * 1e6)));
        }
        
        return results;
    }
    
private:
    // 高级运动目标检测
    static std::vector<cv::Rect> detectMotionTargets(const cv::Mat& frame) {
        std::vector<cv::Rect> targets;
        
        // 多尺度运动检测
        cv::Mat gray, diff;
        cv::cvtColor(frame, gray, cv::COLOR_BGR2GRAY);
        
        static cv::Mat prev_gray;
        if (!prev_gray.empty()) {
            // 帧间差分
            cv::absdiff(prev_gray, gray, diff);
            cv::threshold(diff, diff, 30, 255, cv::THRESH_BINARY);
            
            // 形态学优化
            cv::Mat kernel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(5, 5));
            cv::morphologyEx(diff, diff, cv::MORPH_OPEN, kernel);
            
            // 查找运动区域
            std::vector<std::vector<cv::Point>> contours;
            cv::findContours