#include "common.h"
#include "fetch_log.h"

#include <saas/searchproxy/common/cgi.h>
#include <search/session/reqenv.h>

#include <library/cpp/http/misc/httpreqdata.h>

using namespace NSearchProxy::NLogging;

namespace {
    TString GetServiceName(const TSearchRequestData& rd) {
        TString result = rd.CgiParam.Get(NSearchProxyCgi::service);
        if (result) {
            return result;
        }

        TStringBuf script(rd.ScriptName());
        script = script.After('/');
        return TString(script);
    }
}

void TFetchLog::Log(ui32 id, const TPassageRequestInfo& passageInfo) {
    if (!TLoggerOperator<TFetchLog>::Usage())
        return;

    NUtil::TTSKVRecord record("saas-fetch");
    const TCgiParameters& cgi = passageInfo.RD.CgiParam;

    record.Add(IdLable, id);
    record.Add(HrTimeLable, Now().ToString());
    InsertIncomingInfo(record, passageInfo.RD);
    record.Add(ReplyTimeLable, GetRequestDuration(passageInfo));
    record.ForceAdd(DocRequestedLable, cgi.NumOfValues("dh"));
    record.ForceAdd(DocCountLable, passageInfo.Context.GetSnippets().size());
    record.Add(ServiceLable, GetServiceName(passageInfo.RD));
    record.Add(MetaServiceLable, cgi.Get(NSearchProxyCgi::metaservice));

    TLoggerOperator<TFetchLog>::Log() << record.ToString() << Endl;
}
