#include "data_preprocessor.hpp"

#include <chrono>
#include <stdexcept>
#include <thread>
#include <vector>

namespace radar::preprocessing {

DataPreprocessor::DataPreprocessor(
    const config::RunConfig& config,
    CalibrationMaster& calibration_master,
    ReferenceMaster& reference_master,
    ipc::ShmRing& raw_ring,
    ipc::ShmRing& preprocessed_ring,
    ipc::ShmRing* preprocessed_tap_ring
)
    : config_(config),
      calibration_master_(calibration_master),
      reference_master_(reference_master),
      raw_ring_(raw_ring),
      preprocessed_ring_(preprocessed_ring),
      preprocessed_tap_ring_(preprocessed_tap_ring) {}

void DataPreprocessor::validate_startup_prerequisites() const {
    calibration_master_.validate_combos(config_.run_combos);
    reference_master_.validate_combos(config_.run_combos);
}

auto DataPreprocessor::try_pop_raw_collection(
    std::vector<std::uint8_t>& serialized_raw,
    ipc::RawSweepCollection* out_collection
) -> bool {
    if (!raw_ring_.pop(serialized_raw)) {
        std::this_thread::sleep_for(std::chrono::milliseconds(config_.runtime.idle_sleep_ms));
        return false;
    }

    *out_collection = ipc::deserialize_raw_collection(serialized_raw);
    return true;
}

void DataPreprocessor::publish_preprocessed_collection(const ipc::PreprocessedCollection& collection) {
    const auto serialized_preprocessed = ipc::serialize_preprocessed_collection(collection);
    if (!preprocessed_ring_.push(serialized_preprocessed)) {
        throw std::runtime_error("Preprocessed ring slot is too small for serialized collection");
    }
    if (preprocessed_tap_ring_ != nullptr && !preprocessed_tap_ring_->push(serialized_preprocessed)) {
        throw std::runtime_error("Preprocessed tap ring slot is too small for serialized collection");
    }
}

void DataPreprocessor::run(const std::atomic<bool>& stop_requested) {
    validate_startup_prerequisites();

    std::vector<std::uint8_t> serialized_raw{};
    ipc::RawSweepCollection raw_collection{};
    while (!stop_requested.load(std::memory_order_relaxed)) {
        if (!try_pop_raw_collection(serialized_raw, &raw_collection)) {
            continue;
        }

        const auto preprocessed_collection = preprocess_collection(raw_collection);
        publish_preprocessed_collection(preprocessed_collection);
    }
}

auto DataPreprocessor::preprocess_collection(const ipc::RawSweepCollection& raw_collection) const
    -> ipc::PreprocessedCollection {
    ipc::PreprocessedCollection preprocessed{};
    preprocessed.collection_id = raw_collection.collection_id;
    preprocessed.monotonic_ns = ipc::current_monotonic_ns();
    preprocessed.traces.reserve(raw_collection.traces.size());

    for (const auto& raw_trace : raw_collection.traces) {
        // Pipeline order is fixed: calibration first, then reference subtraction.
        const auto calibrated = calibration_master_.apply(raw_trace);
        const auto referenced = reference_master_.apply(calibrated);
        preprocessed.traces.push_back(referenced);
    }

    return preprocessed;
}

}  // namespace radar::preprocessing
