#include <gflags/gflags.h>
#include <ncode/file.h>
#include <ncode/logging.h>
#include <ncode/lp/demand_matrix.h>
#include <ncode/map_util.h>
#include <ncode/net/net_common.h>
#include <ncode/net/net_gen.h>
#include <ncode/strutil.h>
#include <ncode/thread_runner.h>
#include <chrono>
#include <map>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>

#include "demand_matrix_input.h"
#include "opt/common.h"
#include "opt/ldr.h"
#include "opt/opt.h"
#include "opt/path_provider.h"
#include "topology_input.h"

using namespace std::chrono;

DEFINE_string(rc_file, "", "Routing config file to load.");
DEFINE_string(top_file, "", "Topology file to load.");
DEFINE_string(dm_file, "", "Demand matrix file to load.");


int main(int argc, char** argv) {
    gflags::ParseCommandLineFlags(&argc, &argv, true);
//    LOG(INFO) << "Hello world from TM evaluator. Got RC file to read as " << FLAGS_rc_file;

    std::vector<std::string> node_order;
    nc::net::GraphBuilder builder = nc::net::LoadRepetitaOrDie(nc::File::ReadFileToStringOrDie(FLAGS_top_file), &node_order);
    builder.RemoveMultipleLinks();
    auto graph = nc::make_unique<nc::net::GraphStorage>(builder);

    tm_gen::PathProvider path_provider(graph.get());
    std::unique_ptr<nc::lp::DemandMatrix> demand_matrix = nc::lp::DemandMatrix::LoadRepetitaFileOrDie(FLAGS_dm_file, node_order, graph.get());

    std::unique_ptr<tm_gen::TrafficMatrix> tm =
          tm_gen::TrafficMatrix::DistributeFromDemandMatrix(*demand_matrix);

    std::unique_ptr<tm_gen::RoutingConfiguration> rc =
        tm_gen::RoutingConfiguration::LoadFromSerializedText(*tm, node_order, nc::File::ReadFileToStringOrDie(FLAGS_rc_file), &path_provider);

    std::string out_mlu = nc::StringReplace(FLAGS_rc_file, ".rc", ".mlu", true);
    std::string mlu = std::to_string(rc->MaxLinkUtilization());
    nc::File::WriteStringToFileOrDie(mlu, out_mlu);

//    LOG(INFO) << "Successfully wrote out MLU.";

}
