#if defined(PROJECT_ENABLE_BACKWARD_CPP)
#include "backward.hpp"
#endif // defined(PROJECT_ENABLE_BACKWARD_CPP)

#include "initialize.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/unix.hpp"
#include "utils/windows.hpp"

namespace monitarr {
[[nodiscard]] static auto load_config(std::string &cfg_file) -> app_config {
  MONITARR_USES_FUNCTION_NAME();

  auto cfg_dir = utils::get_environment_variable("MONITARR_CFG_DIR");
  if (cfg_dir.empty()) {
    cfg_dir = utils::path::combine(".", {"config"});
  }

  if (not utils::file::directory{cfg_dir}.create_directory()) {
    throw std::runtime_error(fmt::format("failed to create config dir|{}",
                                         cfg_dir,
                                         utils::get_last_error_code()));
  }

  cfg_file = utils::path::combine(cfg_dir, {"monitarr.json"});

  utils::error::handle_info(function_name,
                            fmt::format("loading config|{}", cfg_file));
  app_config cfg{};
  cfg.load(cfg_file);
  if (not utils::file::file{cfg_file}.exists()) {
    cfg.save(cfg_file);
  }

  return cfg;
}
} // namespace monitarr

using namespace monitarr;

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;
  }

  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)) {
      ret = run_cmd(cfg, cfg_file);
    } 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();
  return ret;
}
