#include "index_verifier.h"

#include <contrib/libs/re2/re2/re2.h>
#include <library/cpp/digest/md5/md5.h>
#include <library/cpp/logger/global/global.h>
#include <apphost/lib/common/mtime.h>

namespace {
    NRTYServer::TJupiIndexVerifier::TFileInfo GetFileInfo(const TFsPath& indexPath) {
        TInstant mtime = GetMtime(indexPath);
        return {indexPath, mtime, MD5::File(indexPath)};
    }
}

namespace NRTYServer {
TJupiIndexVerifier::TJupiIndexVerifier(const TFsPath& directory, const TMaybe<TString>& indexRegex) {
    if (!indexRegex.Defined()) {
        return;
    }

    RE2 re(*indexRegex);
    if (!re.ok()) {
        ERROR_LOG << "Invalid regex '" << *indexRegex << "' . Error details: " << re.error() << Endl;
        return;
    }

    TVector<TString> names;
    directory.ListNames(names);
    for (const TString& candidate : names) {
        if (RE2::FullMatch(candidate, re)) {
            TFsPath indexPath = directory / candidate;
            if (indexPath.IsFile()) {
                RtdocIndexFileInfos.push_back(GetFileInfo(indexPath));
            }
        }
    }
}

i32 TJupiIndexVerifier::Verify(bool crashOnDiff) {
    i32 diffsCount = 0;
    for (const TFileInfo& rtdocInfo : RtdocIndexFileInfos) {
        TFileInfo rtytInfo = GetFileInfo(rtdocInfo.Path); //reading after rtyt job completion
        if (rtdocInfo.MTime == rtytInfo.MTime) {
            ++diffsCount;
            ERROR_LOG << "Diff between rtdoc and rtyt in '" << rtdocInfo.Path.GetName() << "' file: "
                      << "same mtime " << rtdocInfo.MTime << Endl;
        } else if (rtdocInfo.Hash != rtytInfo.Hash) {
            ++diffsCount;
            ERROR_LOG << "Diff between rtdoc and rtyt in '" << rtdocInfo.Path.GetName() << "' file: "
                      << "different hashes " << rtdocInfo.Hash << " (rtdoc) and " << rtytInfo.Hash << " (rtyt)" << Endl;
        }
    }
    if (crashOnDiff) {
        CHECK_WITH_LOG(diffsCount == 0) << "There are " << diffsCount << " diffs between rtdoc and rtyt" << Endl;
    }
    return diffsCount;
}
}
