/*
 * 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.
 */

#include "iceberg/data/equality_delete_writer.h"

#include <map>

#include "iceberg/file_writer.h"
#include "iceberg/manifest/manifest_entry.h"
#include "iceberg/partition_spec.h"
#include "iceberg/util/macros.h"

namespace iceberg {

class EqualityDeleteWriter::Impl {
 public:
  static Result<std::unique_ptr<Impl>> Make(EqualityDeleteWriterOptions options) {
    WriterOptions writer_options{
        .path = options.path,
        .schema = options.schema,
        .io = options.io,
        .properties = WriterProperties::FromMap(options.properties),
    };

    ICEBERG_ASSIGN_OR_RAISE(auto writer,
                            WriterFactoryRegistry::Open(options.format, writer_options));

    return std::unique_ptr<Impl>(new Impl(std::move(options), std::move(writer)));
  }

  Status Write(ArrowArray* data) { return writer_->Write(data); }

  Result<int64_t> Length() const { return writer_->length(); }

  Status Close() {
    if (closed_) {
      return {};
    }
    ICEBERG_RETURN_UNEXPECTED(writer_->Close());
    closed_ = true;
    return {};
  }

  Result<FileWriter::WriteResult> Metadata() {
    ICEBERG_CHECK(closed_, "Cannot get metadata before closing the writer");

    ICEBERG_ASSIGN_OR_RAISE(auto metrics, writer_->metrics());
    ICEBERG_ASSIGN_OR_RAISE(auto length, writer_->length());
    auto split_offsets = writer_->split_offsets();

    // Serialize literal bounds to binary format
    std::map<int32_t, std::vector<uint8_t>> lower_bounds_map;
    for (const auto& [col_id, literal] : metrics.lower_bounds) {
      ICEBERG_ASSIGN_OR_RAISE(auto serialized, literal.Serialize());
      lower_bounds_map[col_id] = std::move(serialized);
    }
    std::map<int32_t, std::vector<uint8_t>> upper_bounds_map;
    for (const auto& [col_id, literal] : metrics.upper_bounds) {
      ICEBERG_ASSIGN_OR_RAISE(auto serialized, literal.Serialize());
      upper_bounds_map[col_id] = std::move(serialized);
    }

    // TODO(anyone): add encryption key metadata for encrypted delete files
    auto data_file = std::make_shared<DataFile>(DataFile{
        .content = DataFile::Content::kEqualityDeletes,
        .file_path = options_.path,
        .file_format = options_.format,
        .partition = options_.partition,
        .record_count = metrics.row_count.value_or(-1),
        .file_size_in_bytes = length,
        .column_sizes = {metrics.column_sizes.begin(), metrics.column_sizes.end()},
        .value_counts = {metrics.value_counts.begin(), metrics.value_counts.end()},
        .null_value_counts = {metrics.null_value_counts.begin(),
                              metrics.null_value_counts.end()},
        .nan_value_counts = {metrics.nan_value_counts.begin(),
                             metrics.nan_value_counts.end()},
        .lower_bounds = std::move(lower_bounds_map),
        .upper_bounds = std::move(upper_bounds_map),
        .split_offsets = std::move(split_offsets),
        .equality_ids = options_.equality_field_ids,
        .sort_order_id = options_.sort_order_id,
        .partition_spec_id =
            options_.spec ? std::make_optional(options_.spec->spec_id()) : std::nullopt,
    });

    FileWriter::WriteResult result;
    result.data_files.push_back(std::move(data_file));
    return result;
  }

  std::span<const int32_t> equality_field_ids() const {
    return options_.equality_field_ids;
  }

 private:
  Impl(EqualityDeleteWriterOptions options, std::unique_ptr<Writer> writer)
      : options_(std::move(options)), writer_(std::move(writer)) {}

  EqualityDeleteWriterOptions options_;
  std::unique_ptr<Writer> writer_;
  bool closed_ = false;
};

EqualityDeleteWriter::EqualityDeleteWriter(std::unique_ptr<Impl> impl)
    : impl_(std::move(impl)) {}

EqualityDeleteWriter::~EqualityDeleteWriter() = default;

Result<std::unique_ptr<EqualityDeleteWriter>> EqualityDeleteWriter::Make(
    const EqualityDeleteWriterOptions& options) {
  ICEBERG_ASSIGN_OR_RAISE(auto impl, Impl::Make(options));
  return std::unique_ptr<EqualityDeleteWriter>(new EqualityDeleteWriter(std::move(impl)));
}

Status EqualityDeleteWriter::Write(ArrowArray* data) { return impl_->Write(data); }

Result<int64_t> EqualityDeleteWriter::Length() const { return impl_->Length(); }

Status EqualityDeleteWriter::Close() { return impl_->Close(); }

Result<FileWriter::WriteResult> EqualityDeleteWriter::Metadata() {
  return impl_->Metadata();
}

std::span<const int32_t> EqualityDeleteWriter::equality_field_ids() const {
  return impl_->equality_field_ids();
}

}  // namespace iceberg
