#include <execution>

#include "run_cmd.hpp"

#include "actions.hpp"
#include "data_db.hpp"
#include "settings.hpp"
#include "utils/common.hpp"
#include "utils/config.hpp"
#include "utils/error.hpp"
#include "utils/file.hpp"
#include "utils/path.hpp"
#include "utils/string.hpp"
#include "utils/time.hpp"
#include "utils/unix.hpp"
#include "utils/windows.hpp"

namespace {
std::mutex mtx;
std::condition_variable notify;
monitarr::stop_type stop_requested{false};

void quit_handler(int sig) {
  MONITARR_USES_FUNCTION_NAME();

  monitarr::utils::error::handle_info(function_name,
                                      fmt::format("stop requested|{}", sig));
  stop_requested = true;

  monitarr::mutex_lock lock(mtx);
  notify.notify_all();
};
} // namespace

namespace monitarr {
static void check_server(const server_cfg &server, data_db &state_db) {
  MONITARR_USES_FUNCTION_NAME();

  utils::error::handle_info(function_name, fmt::format("checking server|{}|{}",
                                                       server.id, server.url));

  auto cli = create_client(server);

  std::uint16_t page{0U};
  while (++page != 0U) {
    httplib::Params params;
    params.emplace("page", std::to_string(page));
    params.emplace("pageSize", "100");

    auto response =
        cli.Get(fmt::format("/api/{}/queue", server.api_version), params, {});
    if (not response) {
      utils::error::handle_error(
          function_name,
          fmt::format("check server request failed|{}|{}|no response",
                      server.id, server.url));
      break;
    }

    if (response->status != httplib::StatusCode::OK_200) {
      utils::error::handle_error(
          function_name, fmt::format("check server request failed|{}|{}|{}",
                                     server.id, server.url, response->status));
      break;
    }

    auto json_data = nlohmann::json::parse(response->body);
    if (json_data.at("page").get<std::uint32_t>() != page) {
      break;
    }

    auto now = utils::time::get_time_now();

    for (const auto &record : json_data.at("records")) {
      auto download_id =
          fmt::format("{}/{}", server.id, record.at("id").get<std::uint64_t>());
      auto episode_id = record.contains("episodeId")
                            ? record["episodeId"].get<std::uint64_t>()
                            : std::uint64_t{0U};
      auto movie_id = record.contains("movieId")
                          ? record["movieId"].get<std::uint64_t>()
                          : std::uint64_t{0U};
      auto size_left = record.at("sizeleft").get<std::uint64_t>();
      auto title = record.at("title").get<std::string>();
      auto is_downloading = utils::string::contains(
          record.at("status").get<std::string>(), "downloading");

      auto data = state_db.get(download_id);
      const auto update_entry = [&download_id, &now, &size_left, &state_db,
                                 &title,
                                 url = server.url](auto last_size_left) {
        if (size_left == 0U) {
          state_db.remove(download_id);
          return;
        }

        utils::error::handle_info(
            function_name, fmt::format("updating {}|{}|{}|{}|{}", download_id,
                                       title, now, size_left, last_size_left));
        state_db.set(data_entry{
            download_id,
            now,
            size_left,
        });
      };

      if (data.has_value()) {
        if (std::chrono::nanoseconds(now - data->last_check) >=
            server.timeout) {
          utils::error::handle_info(
              function_name,
              fmt::format("processing timeout {}|{}|{}|{}|{}", download_id,
                          title, now, size_left, data->size_left));
          if (size_left == data->size_left) {
            remove_stalled(download_id, title, episode_id, movie_id, server,
                           &state_db);
          } else if (size_left == 0U || not is_downloading) {
            state_db.remove(download_id);
          } else {
            update_entry(data->size_left);
          }
        } else if (size_left == 0U || not is_downloading) {
          state_db.remove(download_id);
        }
      } else if (is_downloading && size_left > 0U) {
        update_entry(0U);
      }
    }
  }
}

[[nodiscard]] static auto load_db(std::string_view log_dir) -> data_db {
  MONITARR_USES_FUNCTION_NAME();

  auto data_dir = utils::get_environment_variable("MONITARR_DATA_DIR");
  if (data_dir.empty()) {
    data_dir = utils::path::combine(".", {"data"});
  }

  if (not utils::file::directory{data_dir}.create_directory()) {
    throw utils::error::create_exception(
        function_name, {
                           "failed to create data dir",
                           data_dir,
                           std::to_string(utils::get_last_error_code()),
                       });
  }

  data_db state_db{};
  state_db.open(data_dir, log_dir);
  return state_db;
}

auto run_cmd(const app_config &cfg, std::string_view log_dir) -> int {
  MONITARR_USES_FUNCTION_NAME();

  auto ret{0};
  std::signal(SIGINT, quit_handler);
#if !defined(_WIN32)
  std::signal(SIGQUIT, quit_handler);
#endif // !defined(_WIN32)
  std::signal(SIGTERM, quit_handler);

  try {
    if (cfg.server_list.empty()) {
      utils::error::handle_error(function_name,
                                 "no servers have been configured");
      ret = 3;
    } else {
      auto state_db{load_db(log_dir)};

      while (not stop_requested) {
        std::for_each(std::execution::par, cfg.server_list.begin(),
                      cfg.server_list.end(),
                      [&state_db](const server_cfg &server) {
                        if (stop_requested) {
                          return;
                        }

                        try {
                          check_server(server, state_db);
                        } catch (const std::exception &ex) {
                          utils::error::handle_exception(function_name, ex);
                        } catch (...) {
                          utils::error::handle_exception(function_name);
                        }
                      });
        unique_mutex_lock lock(mtx);
        if (stop_requested) {
          continue;
        }

        utils::error::handle_info(
            function_name,
            fmt::format("waiting for next check|{}", cfg.check_interval));
        notify.wait_for(lock, cfg.check_interval);
      }

      state_db.close();
    }
  } catch (const std::exception &ex) {
    utils::error::handle_exception(function_name, ex);
    ret = 2;
  } catch (...) {
    utils::error::handle_exception(function_name);
    ret = 2;
  }

  utils::error::handle_info(function_name,
                            fmt::format("exiting application|{}", ret));

  return ret;
}
} // namespace monitarr
