//
// Minimal measurement implementation that can actually compile
// This demonstrates the integration with existing RRC task framework
//

#include "task.hpp"
#include "measurement_logic.hpp"
#include <gnb/ngap/task.hpp>
#include <vector>

static constexpr int TIMER_ID_MEASUREMENT = 2001;
static constexpr int TIMER_PERIOD_MEASUREMENT_MS = 5000;

namespace nr::gnb
{

// 启动测量定时器
void GnbRrcTask::initMeasurementTimer()
{
    // 注释掉logger调用避免编译问题
    // m_logger->debug("Starting measurement timer");
    setTimer(TIMER_ID_MEASUREMENT, TIMER_PERIOD_MEASUREMENT_MS);
}

// 测量定时器到期处理
void GnbRrcTask::onMeasurementTimer()
{
    // 重新设置定时器
    setTimer(TIMER_ID_MEASUREMENT, TIMER_PERIOD_MEASUREMENT_MS);
    
    // 遍历所有连接的UE，执行测量和切换判决
    for (auto &[ueId, ueCtx] : m_ueCtx)
    {
        if (ueCtx->state != RrcState::RRC_CONNECTED)
            continue;
            
        // 执行测量报告模拟
        performMeasurementEvaluation(ueId);
    }
}

// 执行测量评估和切换判决
void GnbRrcTask::performMeasurementEvaluation(int ueId)
{
    // 使用头文件中的逻辑
    auto measurement = nr::gnb::measurement::HandoverDecisionEngine::generateSimulatedMeasurement(ueId);
    
    // 切换判决
    int targetGnbId;
    if (nr::gnb::measurement::HandoverDecisionEngine::shouldTriggerHandover(measurement, targetGnbId))
    {
        // 注释掉logger调用
        // m_logger->info("Handover decision: UE {} should handover to gNB {}", ueId, targetGnbId);
        
        // 通过简化方式触发切换
        triggerHandoverToNgap(ueId, targetGnbId);
    }
}

// 其他函数使用头文件中的静态方法
nr::gnb::measurement::UeMeasurementData GnbRrcTask::generateSimulatedMeasurement(int ueId)
{
    return nr::gnb::measurement::HandoverDecisionEngine::generateSimulatedMeasurement(ueId);
}

bool GnbRrcTask::shouldTriggerHandover(const nr::gnb::measurement::UeMeasurementData &measurement, int &targetGnbId)
{
    return nr::gnb::measurement::HandoverDecisionEngine::shouldTriggerHandover(measurement, targetGnbId);
}

int GnbRrcTask::mapPciToGnbId(int pci)
{
    return nr::gnb::measurement::HandoverDecisionEngine::mapPciToGnbId(pci);
}

// 简化的切换触发
void GnbRrcTask::triggerHandoverToNgap(int ueId, int targetGnbId)
{
    // 创建NTS消息发送到NGAP层
    auto msg = std::make_unique<NmGnbRrcToNgap>(NmGnbRrcToNgap::HANDOVER_TRIGGER);
    msg->ueId = ueId;
    msg->targetGnbId = targetGnbId;
    msg->targetCellId = targetGnbId; // 简化映射：cellId = gnbId
    
    // 发送到NGAP任务
    m_base->ngapTask->push(std::move(msg));
    
    // 记录日志（如果logger可用）
    // m_logger->info("Triggered handover for UE {} to gNB {}", ueId, targetGnbId);
}

} // namespace nr::gnb
