/*
  Copyright <2018-2025> <scott.e.graves@protonmail.com>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/
#if defined(PROJECT_ENABLE_BACKWARD_CPP)
#include "backward.hpp"
#endif // defined(PROJECT_ENABLE_BACKWARD_CPP)

#include "initialize.hpp"

#include "actions.hpp"
#include "args.hpp"
#include "block_cmd.hpp"
#include "config_cmd.hpp"
#include "list_cmd.hpp"
#include "run_cmd.hpp"
#include "settings.hpp"
#include "show_cmd.hpp"
#include "usage_cmd.hpp"
#include "utils/common.hpp"
#include "utils/file.hpp"
#include "utils/path.hpp"
#include "utils/unix.hpp"
#include "utils/windows.hpp"

using namespace monitarr;

static constexpr const std::uint8_t MAX_LOG_FILES{5U};
static constexpr const std::uint64_t MAX_LOG_FILE_SIZE{
    1024ULL * 1024ULL * 5ULL,
};

auto main(int argc, char **argv) -> int {
  MONITARR_USES_FUNCTION_NAME();

#if defined(PROJECT_ENABLE_BACKWARD_CPP)
  static backward::SignalHandling sh;
#endif // defined(PROJECT_ENABLE_BACKWARD_CPP)

  if (not utils::file::change_to_process_directory()) {
    utils::error::handle_error(function_name,
                               "failed to change to process directory");
    return -1;
  }

  auto log_dir = utils::get_environment_variable("MONITARR_LOG_DIR");
  if (log_dir.empty()) {
    log_dir = utils::path::combine(".", {"logs"});
  }

  if (not utils::file::directory{log_dir}.create_directory()) {
    utils::error::handle_error(
        function_name, fmt::format("failed to create log dir|{}|{}", log_dir,
                                   utils::get_last_error_code()));
    return -1;
  }

  if (not monitarr::project_initialize()) {
    return -1;
  }

  auto ret{0};

  try {
    std::string cfg_file;
    auto cfg{load_config(cfg_file)};
    if (has_arg("-b", argc, argv)) {
      ret = block_cmd(argc, argv, cfg);
    } else if (has_arg("-c", argc, argv)) {
      ret = config_cmd(cfg);
    } else if (argc == 1 || has_arg("-h", argc, argv)) {
      ret = usage_cmd();
      if (ret == 0 && argc == 1) {
        utils::error::handle_error(function_name, "no arguments specified");
        ret = 1;
      }
    } else if (has_arg("-l", argc, argv)) {
      ret = list_cmd(argc, argv, cfg);
    } else if (has_arg("-r", argc, argv)) {
      spdlog::drop("file");
      spdlog::create_async<spdlog::sinks::rotating_file_sink_mt>(
          "file", utils::path::combine(log_dir, {"monitarr.log"}),
          MAX_LOG_FILE_SIZE, MAX_LOG_FILES);
      ret = run_cmd(cfg, log_dir);
    } else if (has_arg("-s", argc, argv)) {
      ret = show_cmd(argc, argv, cfg);
    } else {
      ret = usage_cmd();
      if (ret == 0) {
        ret = 1;
      }
      utils::error::handle_error(function_name, "invalid argument specified");
    }
  } catch (const std::exception &ex) {
    utils::error::handle_exception(function_name, ex);
    ret = 2;
  } catch (...) {
    utils::error::handle_exception(function_name);
    ret = 2;
  }

  monitarr::project_cleanup();

  utils::error::set_exception_handler(nullptr);
  return ret;
}
