/*
 * Copyright © 2015-2026 Dynare Team
 *
 * This file is part of Dynare.
 *
 * Dynare is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Dynare 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
 */

#include <algorithm>
#include <filesystem>
#include <fstream>
#include <regex>
#include <sstream>

#include "macro/Driver.hh"

stringstream
macroExpandModFile(const filesystem::path& filename, const istream& modfile, bool debug,
                   bool save_macro, filesystem::path save_macro_file, bool line_macro,
                   const vector<pair<string, string>>& defines, vector<filesystem::path> paths)
{
  // Do macro processing
  stringstream macro_output;
  macro::Environment env = macro::Environment();
  macro::Driver m;
  /* Calling string() method on filename: not necessary on GNU/Linux and macOS because there is an
     implicit conversion from filesystem:path to string (i.e. basic_string<char>), but needed on
     Windows because the implicit conversion is only to wstring (i.e. basic_string<wchar_t>). */
  m.parse(filename.string(), modfile, debug, defines, env, paths, macro_output);
  if (save_macro)
    {
      if (save_macro_file.empty())
        save_macro_file = filename.stem().string() + "_macroexp.mod";
      ofstream macro_output_file {save_macro_file};
      if (macro_output_file.fail())
        {
          cerr << "Cannot open " << save_macro_file.string() << " for macro output" << '\n';
          exit(EXIT_FAILURE);
        }

      string str(macro_output.str());
      if (!line_macro)
        {
          // Remove the @#line directives.
          str = regex_replace(str, regex(R"(^@#line.*$)", std::regex::multiline), "");
          /* Remove the EOLs at the beginning of the output, the first one
             being a remnant of the first @#line directive. */
          str = regex_replace(str, regex(R"(^(\r?\n)+)"), "");
          /* Replace sequences of several newlines by a single newline (in
             both LF and CR+LF conventions). */
          str = regex_replace(str, regex(R"(\n{2,})"), "\n");
          str = regex_replace(str, regex(R"((\r\n){2,})"), "\r\n");
        }
      macro_output_file << str;
      macro_output_file.close();
    }
  return macro_output;
}
