#include <util/string/join.h>

#include <library/cpp/getopt/modchooser.h>

#include <wmconsole/version3/wmcutil/args.h>
#include <wmconsole/version3/wmcutil/log.h>
#include <wmconsole/version3/wmcutil/periodic.h>
#include <wmconsole/version3/wmcutil/thread.h>
#include <wmconsole/version3/wmcutil/yt/misc.h>
#include <wmconsole/version3/wmcutil/yt/transfer_manager.h>
#include <wmconsole/version3/wmcutil/yt/yt_runner.h>

#include "config.h"
#include "mirrors.h"
#include "task_report.h"
#include "task_update.h"
#include "week_config.h"

namespace NWebmaster {

int TaskDev(int, const char **) {
    const auto &config = TConfig::CInstance();

    NYT::IClientPtr clientSearch = NYT::CreateClient(config.MR_SERVER_HOST_SEARCH);
    NYT::IClientPtr clientQueries = NYT::CreateClient(config.MR_SERVER_HOST_QUERIES);

    TDigestWeekConfig weekConfig(TWeekConfig(Now().TimeT()).PrevWeek().WeekStart);
    //PrepareIKSSource(clientSearch, weekConfig.ThisWeek);

    THashSet<TString> webmasterHosts;
    if (!NYTUtils::LoadWebmastersHosts(clientQueries, config.TABLE_SOURCE_WEBMASTER_HOSTS, webmasterHosts)) {
        ythrow yexception() << "webmaster hosts table is empty";
    }

    PrepareMirrorsSource(clientSearch, webmasterHosts);
    //BuildDigestReport(clientQueries, clientSearch, weekConfig);

    return 0;
}

} //namespace NWebmaster

int main(int argc, const char **argv) {
    NYT::Initialize(argc, argv);

    using namespace NWebmaster;

    NLastGetopt::TOpts opts;
    TString envRoot;

    opts.AddCharOption('L', "Log path").StoreResult(&TArgs::Instance().LogPath).DefaultValue("");

    opts
        .AddCharOption('E', "Environment root")
        .StoreResult(&envRoot)
        .DefaultValue("prod")
    ;

    TModChooser modChooser;
    modChooser.AddMode("Update",    TaskDailyUpdate,    "TaskDailyUpdate");
    modChooser.AddMode("Report",    TaskBuildReport,    "TaskBuildReport");
    //modChooser.AddMode("Dev",       taskDev,    "TaskBuildReport");

    opts.SetFreeArgDefaultTitle("Task");
    opts.SetFreeArgsMin(1);
    NLastGetopt::TOptsParseResult res(&opts, argc, argv);
    TVector<TString> modeArgs = { res.GetProgramName() };
    TVector<TString> freeArgs = res.GetFreeArgs();
    modeArgs.insert(modeArgs.end(), freeArgs.begin(), freeArgs.end());

    TCustomYTEnvironment::Instance().Init(envRoot);

    TLogger::Instance();
    NYTUtils::DisableLogger();

    return modChooser.Run(modeArgs);
}
