#include "export_masstransit.h"
#include "export_ymapsdf.h"

#include <yandex/maps/wiki/masstransit/convert.h>
#include <maps/libs/log8/include/log8.h>

namespace maps::wiki::exporter {

namespace {

class ExportMasstransit: public ExportViaYmapsdf {
public:
    ExportMasstransit(
            const ExportConfig& exportCfg,
            const ExportFiles& exportFiles)
        : ExportViaYmapsdf(exportCfg, exportFiles)
    {}

protected:
    void ymapsdf2Dump(const std::string& schema) override;
};

void ExportMasstransit::ymapsdf2Dump(const std::string& schema)
{
    const auto& dataErrorLogFilePath = exportFiles_(TmpFile::JSON2YMAPSDF_LOG);

    try {
        masstransit::ymapsdf2mtr(
            exportCfg().ymapsdfPool(),
            schema,
            exportFiles_(TmpFile::DUMP_DIR),
            dataErrorLogFilePath);
    } catch (const maps::Exception& e) {
        ERROR() << e;

        const fs::path logPath{dataErrorLogFilePath};
        if (!fs::exists(logPath) || !fs::file_size(logPath)) {
            throw RuntimeError() << "ymapsdf2mtr failed";
        }

        WARN() << "ymapsdf2mtr failed. Publish errors log to MDS";
        auto dataset = publishMdsErrorDataset(exportCfg(), {logPath.string()});

        throw RuntimeError() << "ymapsdf2mtr failed, log files: " << files(dataset);
    }
}

} // namespace


Datasets exportMasstransitSubset(
    const ExportConfig& exportCfg,
    const ExportFiles& exportFiles)
{
    return ExportMasstransit(exportCfg, exportFiles).run(ResultFile::DUMP_TAR_GZ);
}


} // namespace maps::wiki::exporter

