// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright 2024-2025 Max-Planck-Institut für Nachhaltige Materialien GmbH
// Copyright 2011-2024 Max-Planck-Institut für Eisenforschung GmbH
//
// DAMASK is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
/**
 * @file IO.h
 * @brief C interface to IO.f90 module
 *
 * @author Daniel Otto de Mentock, Max‑Planck‑Institut für Nachhaltige Materialien GmbH
 * @author Martin Diehl, KU Leuven
 * @copyright
 *   Max‑Planck‑Institut für Nachhaltige Materialien GmbH
 */

#pragma once

#include <ISO_Fortran_binding.h>

#include <string_view>

extern "C" void F_IO_error(int error_id, CFI_cdesc_t* msg);

class IO {
public:
  inline static void (*fn)(int error_id, CFI_cdesc_t* msg) = &F_IO_error;
  static void error(int error_id, std::string_view msg) {
    CFI_CDESC_T(0) msg_desc_storage;
    auto* msg_desc = reinterpret_cast<CFI_cdesc_t*>(&msg_desc_storage); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
    CFI_establish(msg_desc,
                  const_cast<char*>(msg.data()), // NOLINT(cppcoreguidelines-pro-type-const-cast)
                  CFI_attribute_other,
                  CFI_type_char,
                  msg.size(),
                  0,
                  nullptr);
    fn(error_id, msg_desc);
  }
};
