#include "table_names.h"
#include "yt_consts.h"

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

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

namespace bg = boost::gregorian;

namespace maps::wiki::route_lost_feedback {

namespace {

const std::string TMP_PREFIX = "//tmp/wiki_maps_route_lost_feedback_";

const int DATE_PERIOD_MAX_SIZE = 31;

} // unnamed namespace


YtTmpTableNames
createYtTmpTableNames()
{
    std::string randomTmpSuffix =
        (std::ostringstream() << boost::uuids::random_generator()()).str();

    YtTmpTableNames res;

    res.routeLostClusters = TMP_PREFIX + "route_lost_clusters" + randomTmpSuffix;
    res.routeLostClustersSorted = TMP_PREFIX + "route_lost_sorted_clusters" + randomTmpSuffix;
    res.trackStat = TMP_PREFIX + "track_stat" + randomTmpSuffix;
    res.trackStatSorted = TMP_PREFIX + "track_stat_sorted" + randomTmpSuffix;
    res.routeLostJoinTrackStat = TMP_PREFIX + "joined_clusters" + randomTmpSuffix;
    res.routeLostScored = TMP_PREFIX + "route_lost_scored" + randomTmpSuffix;
    res.routeLostScoredSorted = TMP_PREFIX + "route_lost_scored_sorted" + randomTmpSuffix;

    return res;
}

YtInputTableNames
createYtInputTableNames(
    boost::gregorian::date_period period,
    NYT::IClient& client)
{
    auto createInputNames = [&](const std::string& path) {
        std::vector<std::string> result;

        for (auto date = period.begin();
            date < period.end() && result.size() < DATE_PERIOD_MAX_SIZE;
            date += bg::days(1))
        {
            std::string tableName = path + "/" + bg::to_iso_extended_string(date);
            if (client.Exists(TString(tableName))) {
                result.emplace_back(tableName);
            } else {
                WARN() << "Table " << tableName << "doesn't exist";
            }
        }

        if (result.size() == DATE_PERIOD_MAX_SIZE) {
            WARN() << "Number of input tables at path '" << path
                   << "' is limited by " << DATE_PERIOD_MAX_SIZE
                   << " (DATE_PERIOD_MAX_SIZE)";
        }

        REQUIRE(
            !result.empty(),
            "No table exists at path '" + path + "' from given period"
        );

        return result;
    };

    YtInputTableNames tableNames;
    tableNames.routeLost = createInputNames(YT_ROUTE_LOST_DIR);
    tableNames.tracks = createInputNames(YT_TRACKS_DIR);

    return tableNames;
}

}  // namespace maps::wiki::route_lost_feedback
