/*
  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.
*/
#include "actions.hpp"

#include "data_db.hpp"
#include "settings.hpp"
#include "utils/common.hpp"
#include "utils/error.hpp"
#include "utils/file.hpp"
#include "utils/path.hpp"
#include "utils/string.hpp"
#include "utils/unix.hpp"
#include "utils/windows.hpp"
#include <optional>

using namespace std::literals::chrono_literals;

namespace monitarr {
auto create_client(const server_cfg &server) -> httplib::Client {
  httplib::Client cli{server.url};
  cli.set_default_headers({
      {"X-Api-Key", server.api_key},
  });

  cli.set_connection_timeout(5s);
  cli.set_read_timeout(5s);
  cli.set_write_timeout(5s);

  return cli;
}

auto get_download(std::uint64_t record_id, const server_cfg &server)
    -> std::optional<nlohmann::json> {
  MONITARR_USES_FUNCTION_NAME();

  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("get download request failed|{}|{}|no response",
                      server.id, server.url));
      return std::nullopt;
    }

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

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

    auto iter = std::ranges::find_if(
        json_data.at("records"),
        [&record_id](const nlohmann::json &record) -> bool {
          return record_id == record.at("id").get<std::uint64_t>();
        });
    if (iter == json_data.at("records").end()) {
      continue;
    }

    return *iter;
  }

  return std::nullopt;
}

auto list_queue(const server_cfg &server) -> int {
  MONITARR_USES_FUNCTION_NAME();

  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("list queue request failed|{}|{}|no response", server.id,
                      server.url));
      return 3;
    }

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

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

    utils::error::handle_info(
        function_name, fmt::format("{}", json_data.at("records").dump(2)));
  }

  return 0;
}

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 utils::error::create_exception(
        function_name, {
                           "failed to create config dir",
                           cfg_dir,
                           std::to_string(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);
  }

  if (cfg.server_list.empty()) {
    return cfg;
  }

  {
    auto iter = std::ranges::adjacent_find(
        cfg.server_list,
        [](auto &&srv1, auto &&srv2) -> bool { return srv1.id == srv2.id; });
    if (iter != cfg.server_list.end()) {
      throw utils::error::create_exception(function_name,
                                           {
                                               "duplicate server found",
                                               iter->id,
                                           });
    }
  }

  {
    constexpr const auto id_names{
        std::array<std::string_view, 3U>{"lidarr", "radarr", "sonarr"},
    };

    auto iter = std::ranges::find_first_of(
        cfg.server_list, id_names, [](auto &&data, auto &&name) -> bool {
          return utils::string::contains(data.id, name);
        });
    if (iter == cfg.server_list.end()) {
      throw utils::error::create_exception(
          function_name,
          {
              "server id must contain one of the following values",
              fmt::format("{}", id_names),
          });
    }
  }

  return cfg;
}

void remove_stalled(std::string_view download_id, std::string_view title,
                    std::uint64_t episode_id, std::uint64_t movie_id,
                    const server_cfg &server, data_db *state_db) {
  MONITARR_USES_FUNCTION_NAME();

  utils::error::handle_info(
      function_name, fmt::format("remove and block {}|{}|{}|{}", server.id,
                                 server.url, title, download_id));

  if (state_db != nullptr) {
    state_db->remove(download_id);
  }

  auto cli = create_client(server);
  auto response = cli.Delete(
      fmt::format("/api/{}/queue/{}?blocklist=true&skipRedownload=false",
                  server.api_version,
                  utils::string::split(download_id, '/', false).at(1U)));
  if (not response) {
    utils::error::handle_error(
        function_name,
        fmt::format("remove stalled request failed|{}|{}|{}|{}|no response",
                    server.id, server.url, title, download_id));
    return;
  }

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

  std::optional<nlohmann::json> data;

  std::uint64_t search_id{};
  if (utils::string::contains("radarr", server.id)) {
    data = nlohmann::json({
        {"name", "MoviesSearch"},
        {"movieIds", {movie_id}},
    });
    search_id = movie_id;
  } else if (utils::string::contains("sonarr", server.id)) {
    data = nlohmann::json({
        {"name", "EpisodeSearch"},
        {"episodeIds", {episode_id}},
    });
    search_id = episode_id;
  }

  if (not data.has_value()) {
    return;
  }

  utils::error::handle_info(
      function_name, fmt::format("searching release {}|{}|{}|{}", server.id,
                                 server.url, title, search_id));
  response = cli.Post(fmt::format("/api/{}/command", server.api_version),
                      data->dump(), "application/json");
  if (not response) {
    utils::error::handle_error(
        function_name, fmt::format("failed to search|{}|{}|{}|{}|no response",
                                   server.id, server.url, title, search_id));
    return;
  }

  if (response->status == httplib::StatusCode::Created_201) {
    return;
  }

  utils::error::handle_error(function_name,
                             fmt::format("failed to search|{}|{}|{}|{}|{}",
                                         server.id, server.url, title,
                                         search_id, response->status));
}
} // namespace monitarr
