#ifndef JTJAI_MEDIA_CONCURRENT_CALCULATOR_H
#define JTJAI_MEDIA_CONCURRENT_CALCULATOR_H

#include "config.h"
#include <vector>
#include <unordered_map>

namespace jtjai_media {

struct StreamScheduleInfo {
    int stream_index;           // 流索引
    int start_time;            // 开始时间（相对于轮询开始的秒数）
    int duration;              // 持续时间（秒）
    int end_time;              // 结束时间
    double priority_score;     // 优先级分数（基于权重计算）
    
    StreamScheduleInfo(int idx, int start, int dur, double score)
        : stream_index(idx), start_time(start), duration(dur), end_time(start + dur), priority_score(score) {}
};

class ConcurrentCalculator {
public:
    ConcurrentCalculator() = default;
    
    // 计算最优的并发调度方案
    std::vector<StreamScheduleInfo> calculate_schedule(
        const std::vector<StreamConfig>& streams,
        int total_duration,
        int max_concurrent
    );
    
    // 获取任意时刻的并发流数量
    int get_concurrent_count_at_time(
        const std::vector<StreamScheduleInfo>& schedule,
        int time_point
    ) const;
    
    // 验证调度方案是否满足约束条件
    bool validate_schedule(
        const std::vector<StreamScheduleInfo>& schedule,
        int total_duration,
        int max_concurrent
    ) const;
    
    // 获取调度统计信息
    struct ScheduleStats {
        int total_streams;
        int max_concurrent_used;
        double average_concurrent;
        int total_scheduled_duration;
        double utilization_rate;
    };
    
    ScheduleStats get_schedule_stats(
        const std::vector<StreamScheduleInfo>& schedule,
        int total_duration
    ) const;
    
    // 输出调度方案的可视化信息
    std::string format_schedule(
        const std::vector<StreamScheduleInfo>& schedule,
        const std::vector<StreamConfig>& streams,
        int total_duration
    ) const;

private:
    // 计算流的优先级分数
    double calculate_priority_score(const StreamConfig& stream) const;
    
    // 贪心算法调度
    std::vector<StreamScheduleInfo> greedy_schedule(
        const std::vector<StreamConfig>& streams,
        int total_duration,
        int max_concurrent
    );
    
    // 寻找最早可用的时间段
    int find_earliest_slot(
        const std::vector<StreamScheduleInfo>& current_schedule,
        int duration,
        int max_concurrent,
        int total_duration
    ) const;
    
    // 检查指定时间段是否可以调度新流
    bool can_schedule_at_time(
        const std::vector<StreamScheduleInfo>& current_schedule,
        int start_time,
        int duration,
        int max_concurrent
    ) const;
    
    // 优化调度方案（尝试减少碎片化）
    std::vector<StreamScheduleInfo> optimize_schedule(
        std::vector<StreamScheduleInfo> schedule,
        int total_duration,
        int max_concurrent
    );
};

} // namespace jtjai_media

#endif // JTJAI_MEDIA_CONCURRENT_CALCULATOR_H