#include "arc_verify.h"

#include <kernel/doom/chunked_wad/doc_chunk_mapping_searcher.h>
#include <kernel/tarc/disk/wad_text_archive.h>
#include <kernel/tarc/iface/tarcio.h>
#include <kernel/doom/chunked_wad/chunked_wad.h>

#include <util/folder/dirut.h>
#include <util/string/builder.h>
#include <util/generic/yexception.h>

namespace NFusion {

    void VerifyPlainArcEqualToChunked(const TString& plainArcPath, const TString& chunkedArchiveDir, const TString& chunkedOutputPrefix) {
        Y_ENSURE(NFs::Exists(plainArcPath), TStringBuilder() << "Plain indexarc file doesn't exists for verify: " << plainArcPath);

        TArchiveIterator plainArcIt;
        plainArcIt.Open(plainArcPath.c_str());

        TWadTextArchiveManager chunkedArc(NDoom::IChunkedWad::OpenChunked(chunkedArchiveDir + "/" + chunkedOutputPrefix + "arc", false), EDataType::DocText);

        Y_ENSURE(chunkedArc.GetDocCount() == plainArcIt.Size(), TStringBuilder() << "chunkedArc.GetDocCount() = " << chunkedArc.GetDocCount() << " != plainArcIt.Size() = " << plainArcIt.Size());

        const ui32 docCount = plainArcIt.Size();
        for (ui32 docId = 0; docId < docCount; ++docId) {
            auto plainItem = plainArcIt.NextAuto();
            Y_ENSURE(plainItem->DocId == docId, TStringBuilder() << "plainItem->DocId = " << plainItem->DocId << " != docId = " << docId);

            Y_ENSURE(!plainItem->ExtLen);
            auto plainData = reinterpret_cast<const char*>(plainItem);
            auto plainText = TBlob::NoCopy(plainData + sizeof(*plainItem), plainItem->DocLen - sizeof(*plainItem));

            const TBlob newText = chunkedArc.GetDocText(docId)->UncompressBlob();

            Y_ENSURE(TStringBuf(newText.AsCharPtr(), newText.Length()) == TStringBuf(plainText.AsCharPtr(), plainText.Length()));

        }
        Y_ENSURE(plainArcIt.NextAuto() == nullptr);
    }

}
