#include "tool.h"

#include <maps/libs/cmdline/include/cmdline.h>
#include <maps/libs/common/include/exception.h>
#include <maps/libs/log8/include/log8.h>
#include <maps/wikimap/mapspro/services/mrc/libs/config/include/config.h>
#include <yandex/maps/wiki/common/pgpool3_helpers.h>

#include <algorithm>
#include <fstream>

namespace mrct = maps::mrc::toloka;

int main(int argc, char* argv[]) try {
    maps::cmdline::Parser parser;
    auto serviceConfig = parser.string("service-config")
        .help("path to service configuration");
    auto toolConfig = parser.string("tool-config")
        .required()
        .help("path to tool configuration");
    auto output = parser.string("output")
        .required()
        .help("output file");
    parser.parse(argc, argv);

    auto cfg = maps::mrc::common::templateConfigFromCmdPath(serviceConfig);
    auto pool = cfg.makePoolHolder();
    auto txn = pool.pool().slaveTransaction();

    auto wkbGeoms = mrct::loadYmapsdfGeometries(toolConfig);
    auto rTree = mrct::makeRTree(wkbGeoms);
    auto ids = mrct::loadAffectedFeatureIds(*txn, rTree);
    std::sort(ids.begin(), ids.end());

    std::ofstream file(output);
    for (auto id : ids) {
        file << id << "\n";
    }
    return EXIT_SUCCESS;
}
catch (const maps::Exception& e) {
    ERROR() << e;
    return EXIT_FAILURE;
}
catch (const std::exception& e) {
    ERROR() << e.what();
    return EXIT_FAILURE;
}
catch (...) {
    ERROR() << "unknown error";
    return EXIT_FAILURE;
}
