#include <chrono>
#include <iomanip>
#include <iostream>
#include <leveldb/db.h>
#include <leveldb/options.h>
#include <numeric>
#include <sstream>
#include <string>
#include <vector>

#include "leveldb/env.h"

#include "gtest/gtest.h"

using namespace leveldb;
// 根据字段值查找所有包含该字段的 key，遍历
std::vector<std::string> FindKeysByField(leveldb::DB* db, const Field& field) {
  std::vector<std::string> keys;
  leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());

  for (it->SeekToFirst(); it->Valid()   ; it->Next()) {
    std::string key = it->key().ToString();
    FieldArray fields;
    db->Get_Fields(leveldb::ReadOptions(), key, fields);
    for (const auto& f : fields) {
      if (f.name == field.name && f.value == field.value) {
        keys.push_back(key);
        break; // 假设每个key中每个字段值唯一
      }
    }
  }
  std::cout << "Found " << keys.size() << " keys" << std::endl;
  delete it;
  return keys;
}

Status OpenDB(std::string dbName, DB** db) {
  Options options;
  options.create_if_missing = true;
  return DB::Open(options, dbName, db);
}

// 吞吐量测试函数
void TestThroughput(leveldb::DB* db, int num_operations) {
  WriteOptions writeOptions;
  auto start_time = std::chrono::steady_clock::now();

  for (int i = 0; i < num_operations; ++i) {
    std::string key = "key_" + std::to_string(i);
    std::string value = "value_" + std::to_string(i);
    db->Put(writeOptions, key, value);
    //    FieldArray fields = {
    //        {"name", "Customer" + std::to_string(i)},
    //        {"address", "Address" + std::to_string(i)},
    //        {"phone", "1234567890"}};
    //    db->Put_Fields(writeOptions, key, fields);
  }
  for (int i = 0; i < num_operations; ++i) {
    std::string key = "key_" + std::to_string(i);
    std::string value;
    db->Get(ReadOptions(), key, &value);
  }

  auto end_time = std::chrono::steady_clock::now();
  auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count();
  std::cout << "Throughput: " << num_operations * 1000 / duration << " OPS" << std::endl;
}

// 延迟测试函数
void TestLatency(leveldb::DB* db, int num_operations, std::vector<int64_t>& lat_res) {
  WriteOptions writeOptions;
  int64_t latency = 0;
  auto end_time = std::chrono::steady_clock::now();
  auto last_time = end_time;
  for (int i = 0; i < num_operations; ++i) {
    // 执行写入操作
    std::string key = "key_" + std::to_string(i);
    //    FieldArray fields = {
    //        {"name", "Customer" + std::to_string(i)},
    //        {"address", "Address" + std::to_string(i)},
    //        {"phone", "1234567890"}};
    //    db->Get_Fields(leveldb::ReadOptions(), key, fields);
    std::string value = "value_" + std::to_string(i);
    db->Put(writeOptions, key, value);

    end_time = std::chrono::steady_clock::now();
    latency = std::chrono::duration_cast<std::chrono::milliseconds>(
                  end_time - last_time).count();
    last_time = end_time;

    lat_res.emplace_back(latency);
  }

  // 输出延迟统计信息（可选）
  double avg_latency = std::accumulate(lat_res.begin(), lat_res.end(), 0.0) / lat_res.size();
  std::cout << "Average Latency: " << std::fixed << std::setprecision(6) << avg_latency << " ms" << std::endl;
  std::cout << "Max Latency: " << *std::max_element(lat_res.begin(), lat_res.end()) << " ms" << std::endl;
  std::cout << "Min Latency: " << *std::min_element(lat_res.begin(), lat_res.end()) << " ms" << std::endl;
}

TEST(TestSchema, Basic) {
  DB* db;
  WriteOptions writeOptions;
  ReadOptions readOptions;
  if (!OpenDB("testdb", &db).ok()) {
    std::cerr << "open db failed" << std::endl;
    abort();
  }
  // 吞吐量测试
  TestThroughput(db, 100000);

  // 延迟测试
  std::vector<int64_t> latency_results;
  TestLatency(db, 100000, latency_results);
  // 关闭数据库
  delete db;
}

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}