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

#include <maps/libs/json/include/value.h>

#include <string>
#include <iomanip>
#include <fstream>
#include <sstream>

namespace {

size_t getBuildingsCount(const std::string& bldsJsonPath) {
    return maps::json::Value::fromFile(bldsJsonPath).size();
}

std::string createPublicationComment(size_t bldsCount) {
    std::stringstream ss;
    ss << std::fixed << std::setprecision(2);
    ss << "Переведите тикет **!!(зел)в работу!!**, чтобы опубликовать"
       << " здания на карту или **!!закройте!!** его,"
       << " чтобы отменить дальнейшее выполнение процесса.\n";
    ss << "Параметры публикации:\n";
    ss << "* Количество зданий: " << bldsCount;
    return ss.str();
}

} // namespace

int main(int argc, const char** argv)
try {
    maps::cmdline::Parser parser("Create publication comment");

    maps::cmdline::Option<std::string> bldsJsonPath = parser.string("blds")
        .required()
        .help("Path to json file with buildings");

    maps::cmdline::Option<std::string> outputPath = parser.string("output")
        .required()
        .help("Path to output text file with comment");

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


    INFO() << "Loading buildings from file: " << bldsJsonPath;
    size_t bldsCount = getBuildingsCount(bldsJsonPath);

    INFO() << "Creating Startrek comment text";
    std::string comment = createPublicationComment(bldsCount);

    INFO() << "Saving comment into file: " << outputPath;
    std::ofstream ofs(outputPath);
    REQUIRE(ofs.is_open(), "Failed to open file: " + outputPath);
    ofs << comment;
    ofs.close();

    return EXIT_SUCCESS;
}
catch (const maps::Exception& e) {
    INFO() << e;
    return EXIT_FAILURE;
}
catch (const std::exception& e) {
    INFO() << e.what();
    return EXIT_FAILURE;
}
catch (...) {
    INFO() << "Caught unknown exception";
    return EXIT_FAILURE;
}
