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

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

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

#include <opencv2/opencv.hpp>

#include <cstdint>
#include <string>


using namespace maps::mrc::carsegm;

int main(int argc, const char** argv) try {
    maps::cmdline::Parser parser("Image car segmentation");

    auto in = parser.string("in")
        .required()
        .help("input image path");

    auto out = parser.string("out")
        .required()
        .help("output mask path");

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

    cv::Mat image = cv::imread(in);
    const cv::Mat mask = CarSegmentator().segment(image);

    for (int i = 0; i < image.rows; ++i) {
        for (int j = 0; j < image.cols; ++j) {
            if (mask.at<bool>(i, j)) {
                image.at<cv::Vec3b>(i, j)[2] = 255;
            }
        }
    }

    REQUIRE(cv::imwrite(out, image), "Impossible to store mask to file" << out);

    return EXIT_SUCCESS;
} catch (const maps::Exception& ex) {
    FATAL() << "Failed: " << ex;
    return EXIT_FAILURE;
} catch (const yexception& ex) {
    FATAL() << "Failed: " << ex.what();
    if (ex.BackTrace()) {
        FATAL() << ex.BackTrace()->PrintToString();
    }
    return EXIT_FAILURE;
} catch (const std::exception& ex) {
    FATAL() << "Failed: " << ex.what();
    return EXIT_FAILURE;
}
