#pragma once

#include <array>
#include <cstddef>
#include <cstdint>
#include <map>
#include <optional>
#include <span>
#include <vector>

#include <fesa/model/domain.hpp>

namespace fesa {

enum class NodeDof : std::uint8_t {
    ux,
    uy,
    uz,
    rx,
    ry,
    rz,
};

struct DofAddress final {
    NodeId node;
    NodeDof dof;
};

class DofManager final {
public:
    [[nodiscard]] static DofManager build(const Domain& domain);

    [[nodiscard]] std::size_t full_dof_count() const noexcept;
    [[nodiscard]] std::size_t free_equation_count() const noexcept;
    [[nodiscard]] std::optional<std::size_t> equation(
        DofAddress address) const;
    [[nodiscard]] std::optional<std::size_t> equation(
        std::size_t full_dof) const;
    [[nodiscard]] std::optional<double> prescribed_value(
        DofAddress address) const;
    [[nodiscard]] std::optional<double> prescribed_value(
        std::size_t full_dof) const;
    [[nodiscard]] std::size_t full_dof(DofAddress address) const;
    [[nodiscard]] std::array<std::size_t, 12> element_full_dofs(
        const BeamElement& element) const;
    [[nodiscard]] std::vector<double> reconstruct_full(
        std::span<const double> reduced) const;

private:
    [[nodiscard]] std::size_t node_full_dof_base(NodeId node) const;

    std::map<std::int64_t, std::size_t> node_full_dof_bases_;
    std::vector<std::optional<std::size_t>> equations_;
    std::vector<double> prescribed_values_;
    std::size_t free_equation_count_ = 0;
};

}  // namespace fesa
