#include "fesa/math/vector.hpp"

#include <mkl.h>

#include <limits>
#include <stdexcept>
#include <utility>

namespace fesa {
namespace {

MKL_INT toMklSize(const std::size_t size) {
    if (size > static_cast<std::size_t>((std::numeric_limits<MKL_INT>::max)())) {
        throw std::length_error{"Dense vector size exceeds the MKL integer range."};
    }
    return static_cast<MKL_INT>(size);
}

void copyValues(const std::vector<double>& source, std::vector<double>& destination) {
    if (source.empty()) {
        return;
    }

    // Keep the backend operation in this translation unit so public ownership
    // remains independent of MKL headers and integer types.
    cblas_dcopy(toMklSize(source.size()), source.data(), 1, destination.data(), 1);
}

} // namespace

Vector::Vector(const std::size_t size, const double value)
    : values_(size, value) {}

Vector::Vector(const Vector& other)
    : values_(other.size()) {
    copyValues(other.values_, values_);
}

Vector::Vector(Vector&& other) noexcept
    : values_(std::move(other.values_)) {
    other.values_.clear();
}

Vector& Vector::operator=(const Vector& other) {
    if (this != &other) {
        std::vector<double> copied(other.size());
        copyValues(other.values_, copied);
        values_.swap(copied);
    }
    return *this;
}

Vector& Vector::operator=(Vector&& other) noexcept {
    if (this != &other) {
        values_ = std::move(other.values_);
        other.values_.clear();
    }
    return *this;
}

std::size_t Vector::size() const noexcept {
    return values_.size();
}

double* Vector::data() noexcept {
    return values_.data();
}

const double* Vector::data() const noexcept {
    return values_.data();
}

double& Vector::operator[](const std::size_t index) {
    return values_.at(index);
}

const double& Vector::operator[](const std::size_t index) const {
    return values_.at(index);
}

double Vector::dot(const Vector& rhs) const {
    if (size() != rhs.size()) {
        throw std::invalid_argument{"Vector dot product requires equal dimensions."};
    }
    if (values_.empty()) {
        return 0.0;
    }

    return cblas_ddot(toMklSize(size()), data(), 1, rhs.data(), 1);
}

double Vector::norm() const {
    if (values_.empty()) {
        return 0.0;
    }

    return cblas_dnrm2(toMklSize(size()), data(), 1);
}

void Vector::scale(const double alpha) {
    if (values_.empty()) {
        return;
    }

    cblas_dscal(toMklSize(size()), alpha, data(), 1);
}

void Vector::axpy(const double alpha, const Vector& x) {
    if (size() != x.size()) {
        throw std::invalid_argument{"Vector axpy requires equal dimensions."};
    }
    if (values_.empty()) {
        return;
    }

    cblas_daxpy(toMklSize(size()), alpha, x.data(), 1, data(), 1);
}

} // namespace fesa
