/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include <memory>

#include "paimon/common/compression/block_compression_factory.h"
#include "paimon/common/sst/block_cache.h"
#include "paimon/common/sst/block_handle.h"
#include "paimon/common/sst/block_iterator.h"
#include "paimon/common/sst/block_reader.h"
#include "paimon/common/sst/block_trailer.h"
#include "paimon/common/sst/bloom_filter_handle.h"
#include "paimon/common/utils/bit_set.h"
#include "paimon/common/utils/bloom_filter.h"
#include "paimon/fs/file_system.h"
#include "paimon/memory/bytes.h"
#include "paimon/result.h"

namespace paimon {
class SstFileIterator;

/// An SST File Reader which serves point queries and range queries. Users can call
/// CreateIterator() to create a file iterator and then use seek and read methods to do range
/// queries. Note that this class is NOT thread-safe.
class PAIMON_EXPORT SstFileReader {
 public:
    static Result<std::shared_ptr<SstFileReader>> Create(
        const BlockHandle& index_block_handle,
        const std::optional<BloomFilterHandle>& bloom_filter_handle,
        MemorySlice::SliceComparator comparator, const std::shared_ptr<BlockCache>& block_cache,
        const std::shared_ptr<MemoryPool>& pool);

    /// Create an SstFileReader by reading the SortLookupStoreFooter from the given InputStream.
    /// This method encapsulates the common pattern of reading the footer, parsing it, and
    /// creating the reader, which avoids code duplication across callers.
    static Result<std::shared_ptr<SstFileReader>> CreateForSortLookupStore(
        const std::shared_ptr<InputStream>& input, MemorySlice::SliceComparator comparator,
        const std::shared_ptr<BlockCache>& block_cache, const std::shared_ptr<MemoryPool>& pool);

    ~SstFileReader() {
        [[maybe_unused]] Status _ = Close();
    }

    /// Create an iterator for the index block.
    std::unique_ptr<BlockIterator> CreateIndexIterator();

    /// Lookup the specified key in the file.
    ///
    /// @param key serialized key
    /// @return corresponding serialized value, nullptr if not found.
    Result<std::shared_ptr<Bytes>> Lookup(const std::shared_ptr<Bytes>& key);

    Result<std::unique_ptr<BlockIterator>> GetNextBlock(
        std::unique_ptr<BlockIterator>& index_iterator);

    /// @param handle The block handle.
    /// @param index Whether read the block as an index.
    /// @return The reader of the target block.
    Result<std::shared_ptr<BlockReader>> ReadBlock(const BlockHandle& handle, bool index);

    Status Close();

 private:
    static Result<MemorySegment> DecompressBlock(const MemorySegment& compressed_data,
                                                 const std::shared_ptr<BlockTrailer>& trailer,
                                                 const std::shared_ptr<MemoryPool>& pool);

    SstFileReader(const std::shared_ptr<MemoryPool>& pool,
                  const std::shared_ptr<BlockCache>& block_cache,
                  const std::shared_ptr<BloomFilter>& bloom_filter,
                  const std::shared_ptr<BlockReader>& index_block_reader,
                  MemorySlice::SliceComparator comparator);

 private:
    std::shared_ptr<MemoryPool> pool_;
    std::shared_ptr<BlockCache> block_cache_;
    std::shared_ptr<BloomFilter> bloom_filter_;
    std::shared_ptr<BlockReader> index_block_reader_;
    MemorySlice::SliceComparator comparator_;
};

}  // namespace paimon
