#include <maps/wikimap/mapspro/services/mrc/libs/db/include/common.h>

#include <maps/libs/http/include/http.h>

#include <maps/libs/cmdline/include/cmdline.h>
#include <maps/libs/log8/include/log8.h>
#include <maps/libs/common/include/exception.h>

using namespace maps;
using namespace maps::mrc;

namespace {

void hideHypothesis(
    http::Client& httpClient,
    const std::string& socialHost,
    size_t uid,
    db::TId hypothesisId)
{
    http::URL url = "http://" + socialHost + "/feedback/tasks/" + std::to_string(hypothesisId) + "/hide";
    url.addParam("uid", uid);

    maps::common::retry(
        [&]() {
            auto request = http::Request(httpClient, http::POST, url);
            return request.perform();
        },
        maps::common::RetryPolicy().setTryNumber(3)
    );
}

}; // namespace

int main(int argc, const char* argv[]) try {
    cmdline::Parser parser("Hide hypotheses");

    maps::cmdline::Option<std::string> socialHost = parser.string("social_host")
        .required()
        .help("Social host. Example: core-nmaps-social.maps.yandex.net (without http:// !)");

    maps::cmdline::Option<size_t> uid = parser.size_t("uid")
        .required()
        .help("NMaps uid");

    maps::cmdline::Option<std::string> hypothesesPath = parser.string("hypotheses")
        .required()
        .help("Path to text file with hypothesis ids");

    parser.parse(argc, const_cast<char**>(argv));

    std::ifstream hypothesesIfs(hypothesesPath);
    REQUIRE(hypothesesIfs.is_open(), "Failed to open file: " << hypothesesPath);

    http::Client httpClient;
    httpClient.setTimeout(std::chrono::seconds(1));

    size_t hiddenHypothesesCount = 0;

    db::TId hypothesisId;
    while (hypothesesIfs >> hypothesisId) {
        INFO() << "Hide hypothesis: " << hypothesisId;;
        hideHypothesis(httpClient, socialHost, uid, hypothesisId);
        INFO() << "Done!";
        hiddenHypothesesCount++;
    }

    INFO() << "Hidden hypotheses " << hiddenHypothesesCount;

    return EXIT_SUCCESS;
} catch (const maps::Exception& ex) {
    std::cerr << "Failed maps::Exception: " << ex << std::endl;
    return EXIT_FAILURE;
} catch (const std::exception& ex) {
    std::cerr << "Failed std::exception: " << ex.what() << std::endl;
    return EXIT_FAILURE;
}
