
#ifdef __cplusplus
extern "C"
{
#endif

#include "postgres.h" // 与 #include <iomanip> 冲突
//为了解决和libintl.h冲突的问题undef以下4个
#undef gettext
#undef dgettext
#undef ngettext
#undef dngettext

#include "utils/palloc.h"
#include "utils/memutils.h"

#include "nodes/nodes.h"
#include "nodes/parsenodes.h"
#include "nodes/value.h"

#include "base64.h"

#include <string.h>
#ifdef __cplusplus
}
#endif

#include "encryptsql/fieldmap.h"
#include <assert.h>
#include <stdexcept>
#include <set>
#include <vector>
#include <string>
#include "libpq-fe.h"  // 改为使用引号包含

#include "crypto/crypto.h"
#include "crypto/openssl.h"
#include "encryptsql.h"


#include <regex>
#include <iostream>
#include <unordered_set>

#include "en_config.h"
#include "kms/kms_core_local.hpp"
#include "kms/kms_factory.hpp"

void connectionRotationSelectDek(const std::string &user_name, std::map<std::string, std::string> &_dek_tmp, bool &hasDEK);
void connectionRotationUpdataDek(const std::string &user_name, std::map<std::string, std::string> &_dek_tmp);

// 读取文件内容为字节数组
std::vector<unsigned char> LocalKmsCore::readBinaryFile(const std::string& path){
    std::ifstream file(path, std::ios::binary);
    if (!file) throw std::runtime_error("Failed to open file: " + path);
    return std::vector<unsigned char>((std::istreambuf_iterator<char>(file)), {});
}

// XOR 两段数据
std::vector<unsigned char> LocalKmsCore::xorBuffers(const std::vector<unsigned char>& a, const std::vector<unsigned char>& b) {
    size_t len = std::min(a.size(), b.size());
    std::vector<unsigned char> out(len);
    for (size_t i = 0; i < len; ++i)
        out[i] = a[i] ^ b[i];
    return out;
}

// 计算 HMAC-SHA256
std::vector<unsigned char> LocalKmsCore::hmac_sha256(const std::vector<unsigned char>& key,
                                       const std::vector<unsigned char>& message) {
    unsigned char* result;
    unsigned int len = SHA256_DIGEST_LENGTH;
    result = HMAC(EVP_sha256(), key.data(), key.size(), message.data(), message.size(), nullptr, nullptr);
    return std::vector<unsigned char>(result, result + len);
}

// 读取系统主板序列号并转为 16 字节 hash
std::vector<unsigned char> LocalKmsCore::getSystemIDHash16() {
    std::ifstream file("/sys/class/dmi/id/board_serial");
    if (!file) throw std::runtime_error("Failed to read board_serial.");
    std::ostringstream oss;
    oss << file.rdbuf();
    std::string id = oss.str();

    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256(reinterpret_cast<const unsigned char*>(id.data()), id.size(), hash);
    return std::vector<unsigned char>(hash, hash + 16);  // 只取前16字节
}

void LocalKmsCore::getRootKey(unsigned char *key, size_t len) {
    auto A = readBinaryFile(ROOT_KEY_GEN_PATH "/frag_a");
    auto B = readBinaryFile(ROOT_KEY_GEN_PATH "/frag_b");
    auto C = readBinaryFile(ROOT_KEY_GEN_PATH "/frag_c");

    if (A.size() != B.size() || A.size() != C.size() || A.size() != 16)
        throw std::runtime_error("All key fragments must be 16 bytes.");

    // Step 2: A ⊕ B = X
    auto X = xorBuffers(A, B);

    // Step 3: HMAC(C, X) = Y
    auto Y_full = hmac_sha256(C, X);  // 32字节

    // Step 4: 取前16字节，和主板ID派生出的16字节 hash 做 XOR
    auto Y16 = std::vector<unsigned char>(Y_full.begin(), Y_full.begin() + 16);
    auto sysID = getSystemIDHash16();

//        auto FinalKey = xorBuffers(Y16, sysID);
    auto FinalKey = xorBuffers(Y16, sysID);
    for (size_t i = 0; i < len; ++i) {
        key[i] = FinalKey[i];
    }
}

std::vector<unsigned char> LocalKmsCore::sha256(const std::string& input) {
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, input.c_str(), input.length());
    SHA256_Final(hash, &sha256);
    return std::vector<unsigned char>(hash, hash + SHA256_DIGEST_LENGTH);
}

std::string LocalKmsCore::deriveKey(const std::string& master_key, const std::string& column_name) {
    // 使用列名生成盐值
    std::string salt = generateSalt(column_name);

    // 加入时间戳(ms)
    auto now = std::chrono::system_clock::now();
    auto now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
    
    // 组合主密钥、盐值和时间戳
    std::stringstream combined;
    combined << master_key << salt << "_" << now_ms.count();

    // 使用SHA-256进行密钥派生
    auto derived = sha256(combined.str());
    
    // 将派生的密钥转换为可打印字符串
    std::stringstream ss;
    for(unsigned char byte : derived) {
        if(byte >= 32 && byte <= 126) { // 只使用可打印字符
            ss << static_cast<char>(byte);
        } else {
            ss << static_cast<char>((byte % (126-32+1)) + 32); // 映射到可打印字符范围
        }
    }
    
    // 确保输出长度为16字节
    std::string result = ss.str().substr(0, 16);
    return result;
}

std::string LocalKmsCore::generateSalt(const std::string& column_name) {
    // 使用列名作为盐值的基础
    std::string base = "KMS_SALT_COL_";
    if (column_name.empty()) {
        // 如果列名为空，说明是表级密钥
        base += "TABLE_KEY";
    } else {
        base += column_name;
    }
    return base;
}

bool LocalKmsCore::getRandomCmk(std::string &_cmk_data, AlgorithmType alg, int &length) {
    switch (alg) {
        case AES128:
        case SM4:
            length = 16;
            break;
        default:
            return false;
    }
    _rand(_cmk_data, length);
    return true;
}

bool LocalKmsCore::getRandomDek(std::string &_dek_data) {
    int tmp_length = 16;
    _rand(_dek_data, tmp_length);
    encryptData(_dek_data);
    return true;
}


void LocalKmsCore::_rand(std::string &rand, int length_in_bytes) {
    int cur = 0;
    rand.resize(length_in_bytes);  // 确保 rand 有足够的空间

    // 使用更高质量的随机数生成器
    std::random_device rd;
    std::mt19937 gen(rd());  // 初始化随机数生成器
    std::uniform_int_distribution<> dis(0, 255);  // 生成范围在 [0, 255] 之间的随机数

    while (cur < length_in_bytes) {
        auto random = dis(gen);  // 获取一个随机字节
        if (random >= 32 && random <= 126) // 进一步限制生成的字节范围
        {
            rand[cur] = static_cast<char>(random);
            cur++;
        } else {
            continue;
        }
    }
}


bool LocalKmsCore::encryptKey(std::string &ori_key) {
    constexpr int key_size = 16;
    int block_size = AES_BLOCK_SIZE;
    int ori_key_len = ori_key.size();

    if (ori_key_len % block_size != 0) {
        int padding_len = block_size - (ori_key_len % block_size);
        ori_key.append(padding_len, '\0');  // 填充ori_key
    }
    // 设置密钥
    unsigned char key[key_size] = {0};
    getRootKey(key, key_size);
    // std::ifstream file(_key_path, std::ios::binary);
    // if (file) {
    //     file.read(reinterpret_cast<char *>(key), key_size);

    //     size_t bytesRead = file.gcount();
    //     if (bytesRead < key_size) {
    //         std::cerr << "warning: domiankeysize is shorter than 16, filling with 0!" << std::endl;
    //     }
    //     file.close();
    // } else {
    //     std::cerr << "cannot open domainkey!" << std::endl;
    //     return -1;
    // }
    // 创建加密上下文
    AES_KEY encrypt_key;
    if (AES_set_encrypt_key(key, 128, &encrypt_key) < 0) {
        std::cerr << "Failed to set AES encryption key!" << std::endl;
        return false;
    }
    std::string encrypted(ori_key.size(), '\0');
    unsigned char *input_data = reinterpret_cast<unsigned char *>(&ori_key[0]);
    unsigned char *output_data = reinterpret_cast<unsigned char *>(&encrypted[0]);

    for (size_t i = 0; i < ori_key.size(); i += block_size) {
        AES_ecb_encrypt(input_data + i, output_data + i, &encrypt_key, AES_ENCRYPT);
    }
    //为了实现存储json改为base64编码，KeyStruct _struct编码结构是否需要修改？
    std::string base64_encrypted = base64_encode(reinterpret_cast<const unsigned char *>(encrypted.c_str()),
                                                 encrypted.size());
    ori_key = base64_encrypted;

    return true;
}

bool LocalKmsCore::decryptKey(std::string &ori_key) {
    const int key_size = 16;
    int block_size = AES_BLOCK_SIZE;

    std::string decoded = base64_decode(ori_key);

    unsigned char key[key_size] = {0};
    getRootKey(key, key_size);
    // std::ifstream file(_key_path, std::ios::binary);
    // if (file) {
    //     file.read(reinterpret_cast<char *>(key), key_size);

    //     size_t bytesRead = file.gcount();
    //     if (bytesRead < key_size) {
    //         std::cerr << "warning: domiankeysize is shorter than 16, filling with 0!" << std::endl;
    //     }
    //     file.close();
    // } else {
    //     std::cerr << "cannot open domainkey!" << std::endl;
    //     return false;
    // }


    AES_KEY decrypt_key;
    if (AES_set_decrypt_key(key, 128, &decrypt_key) < 0) {
        std::cerr << "Failed to set AES decryption key!" << std::endl;
        return false;
    }

    std::string decrypted(decoded.size(), '\0');
    unsigned char *input_data = reinterpret_cast<unsigned char *>(&decoded[0]);
    unsigned char *output_data = reinterpret_cast<unsigned char *>(&decrypted[0]);

    for (size_t i = 0; i + block_size <= decoded.size(); i += block_size) {
        AES_ecb_encrypt(input_data + i, output_data + i, &decrypt_key, AES_DECRYPT);
    }
    // 去除填充的\0
    size_t last_non_null_pos = decrypted.find_last_not_of('\0');
    if (last_non_null_pos != std::string::npos) {
        decrypted.erase(last_non_null_pos + 1);  // 删除从最后一个非零字符后的所有填充字符
    }
    ori_key = decrypted;

    return true;

}

std::string LocalKmsCore::base64_encode(const unsigned char *data, size_t length) {
    // 计算编码后的长度 (每3字节编码成4字节，所以需要根据长度调整)
    size_t encode_length = 4 * ((length + 2) / 3);
    std::string encoded;
    encoded.resize(encode_length);

    int actual_size = EVP_EncodeBlock(reinterpret_cast<unsigned char *>(&encoded[0]), data, length);

    if (actual_size < 0) {
        throw std::runtime_error("Base64 encoding failed");
    }

    return encoded;
}

std::string LocalKmsCore::base64_decode(const std::string &encoded) {
    size_t decode_length = encoded.size() * 3 / 4;

    // 在解码时，OpenSSL 会根据 Base64 编码内容自动填充 \0
    std::string decoded;
    decoded.resize(decode_length);

    int actual_size = EVP_DecodeBlock(reinterpret_cast<unsigned char *>(&decoded[0]),
                                      reinterpret_cast<const unsigned char *>(encoded.c_str()),
                                      encoded.size());

    if (actual_size < 0) {
        throw std::runtime_error("Base64 decoding failed");
    }
    decoded.resize(actual_size);
    return decoded;
}

bool LocalKmsCore::createDerivedDek(std::string& dek, const std::string& column_name) {
    // 获取当前用户的CMK
    if (_cmk == "") {
        return false;
    }
    
    // 从CMK派生DEK，使用传入的列名作为盐值
    dek = deriveKey(_cmk, column_name);
    
    // 使用CMK加密派生的DEK
    encryptData(dek);
    return true;
}


// 读取持久化的自动轮转状态
void LocalKmsCore::loadAutoRotateStatus() {
    std::ifstream file(_cmk_auto_rotate_status_path, std::ios::in);
    if (file.is_open()) {
        json cmk_rotate_status = json::parse(file);
        file.close();
        for (auto &entry : cmk_rotate_status.items()) {
            cmk_auto_rotate_status[entry.key()] = entry.value()["status"];
            cmk_auto_rotate_pids[entry.key()] = entry.value()["pid"];
        }
    }
}



// 保存自动轮转状态到文件
void LocalKmsCore::saveAutoRotateStatus() {
    json cmk_rotate_status;
    for (auto &entry : cmk_auto_rotate_status) {
        cmk_rotate_status[entry.first] = {
            {"status", entry.second},
            {"pid", cmk_auto_rotate_pids[entry.first]}
        };
    }
    std::ofstream outFile(_cmk_auto_rotate_status_path);
    if (outFile.is_open()) {
        outFile << cmk_rotate_status.dump(4);
        outFile.close();
    }
}

// 进程函数，用于自动轮转CMK
void LocalKmsCore::autoRotateProcess(const std::string &user_name) {
    signal(SIGTTOU, SIG_IGN); // 忽略挂起信号
    signal(SIGTTIN, SIG_IGN);

    int check_period = 10;    // 检查间隔天数
    int check_period_hours = check_period * 24;
    std::time_t check_time = std::time(nullptr);

    // 使用互斥锁保护进程
    static std::mutex check_mutex;

    while (true) {
        std::lock_guard<std::mutex> lock(check_mutex);

        std::time_t now = std::time(nullptr);
        tm *localtime = std::localtime(&now);

        //0点整检查
        if (localtime->tm_hour == 0 && localtime->tm_min == 0 && localtime->tm_sec == 0) {
            if (std::difftime(now, check_time) >= check_period * 24 * 60 * 60) {
                std::cout << "Checking CMK automatical rotation for user: " << user_name << " (PID: " << getpid() << ")" << std::endl;

                // 读取CMK信息开始检查
                std::ifstream file(_path, std::ios::in);
                if (file.is_open()) {
                    json data = json::parse(file);
                    file.close();

                    int cmk_id = data["index"][user_name];
                    json cmk = data["cmk"][std::to_string(cmk_id)];
                    int rotate_period = cmk["rotate_period"];
                    std::time_t create_time = cmk["create_time"];

                    // 计算时间差
                    std::time_t time_diff = std::difftime(now, create_time);

                    // 如果时间差大于或等于轮转周期，则进行轮转
                    if (time_diff >= rotate_period * 24 * 60 * 60) {
                        std::cout << "Rotating CMK automatically for user: " << user_name << std::endl;
                        rotateCmkNow(user_name);
                        // 轮转时，等待3秒以避免高频检查
                        std::this_thread::sleep_for(std::chrono::seconds(3));
                    }
                }
                check_time = std::time(nullptr);
                //防止查询阻塞
                std::this_thread::sleep_for(std::chrono::seconds(3));
            }
        }
    }
}


//TODO 更新store会出错的条件
bool LocalKmsCore::storeCmk(CMK &cmk, bool rotate) {

    //判断该用户是否已有CMK
    if (hasCmk(cmk._user_name) && !rotate) {
        std::cout << cmk._user_name << " already has a cmk." << std::endl;
        return false;
    }
    //printf("cmk._cmk_data_plain: %s\n", cmk._cmk_data.c_str());

    //存储之前先加密_cmk_data，让它以密文形式存储
    encryptKey(cmk._cmk_data);

    //更新cmk数组
    _data["cmk"][std::to_string(cmk._key_id)] = {
            {"user",        cmk._user_name},
            {"length",      cmk._length},
            {"struct",      cmk._struct},
            {"alg",         cmk._alg},
            {"cmk_data",    cmk._cmk_data},
            {"rotate_period",       cmk._rotate_period},
            {"create_time",         cmk._create_time},
            {"is_rotated",          cmk._is_rotated},
            {"is_primary_version",  cmk._is_primary_version}
    };

    //更新index
    _data["index"][cmk._user_name] = cmk._key_id;

    //更新current_id
    _data["current_id"] = cmk._key_id + 1;
    save();
    init();
    return true;
}

bool LocalKmsCore::LoadCmkByUsername(const std::string &user_name) {
    if (user_name.empty()) {
        return false;
    }
    if (!hasCmk(user_name)) {
        return false;
    }

    std::string tmp_cmk = _data["cmk"][std::to_string((int) _data["index"][user_name])]["cmk_data"];
    decryptKey(tmp_cmk);

    _user_name = user_name;
    _cmk = tmp_cmk;
    return true;
}

bool LocalKmsCore::save() {
    std::ofstream outFile(_path);
    if (outFile.is_open()) {
        outFile << _data.dump(4);
        outFile.close();
    }
    return true;
}





/* ------------------------------接口方法------------------------------------ */

LocalKmsCore::LocalKmsCore(const IKmsConfig& config_) {
    auto config = dynamic_cast<const LocalKmsConfig&>(config_);
    _path = config.file_path_;
    _key_path = config.key_path_;
    _cmk_auto_rotate_status_path = config.cmk_auto_rotate_status_path_;
    _user_name = config.user_name_;
    _db_name = config.db_name_;;
}

LocalKmsCore::~LocalKmsCore() {
    save();
}

//
bool LocalKmsCore::init() {
    std::ifstream file(_path, std::ios::in);
    if (file.is_open()) {
        _data = json::parse(file);
    } else {
        _data["cmk"] = json::object();
        _data["index"] = json::object();
        _data["current_id"] = 0;
        std::ofstream outFile(_path);
        if (outFile.is_open()) {
            outFile << _data.dump(4);
            outFile.close();
        }
    }

    LoadCmkByUsername(_user_name);
    return true;
}

bool LocalKmsCore::hasCmk(const std::string &user_name) const {
    if (_data["index"].contains(user_name)) {
        return true;
    }
    return false;
}

bool LocalKmsCore::createCmk(const std::string &user_name, int rotate_period , KeyStruct ks, AlgorithmType alg) {
    CMK new_cmk;
    new_cmk._alg = alg;
    new_cmk._struct = ks;
    new_cmk._user_name = user_name;
    new_cmk._create_time = time(nullptr);
    new_cmk._rotate_period = rotate_period;
    new_cmk._is_rotated = false;            //新密钥状态未被轮转
    new_cmk._is_primary_version = true;     //新密钥设为主版本
    //创建时初始化CMK轮转状态
    cmk_auto_rotate_status[user_name] = false;
    if (getRandomCmk(new_cmk._cmk_data, alg, new_cmk._length)) {
        //TODO :use log
        printf("getRandomCmk successfully!\n");
        printf("cmk_data_plain: %s\n", new_cmk._cmk_data.c_str());
    } else {
//		printf("getRandomCmk error!\n");
        return false;
    };
    new_cmk._key_id = _data["current_id"];
    
    storeCmk(new_cmk, true);
    return true;
}

bool LocalKmsCore::deleteCmk(const std::string &user_name) {
    if (!hasCmk(user_name)) {
        std::cout << "No CMK found for user: " << user_name << std::endl;
        return false;
    }

    int cmk_id = _data["index"][user_name];
    // 修改CMk主版本状态
    _data["cmk"][std::to_string(cmk_id)]["is_primary_version"] = false;
    //删除index
    _data["index"].erase(user_name);
    //若该用户CMK自动轮转进程开启中，将对应进程关闭，再删除自动轮转状态
    if (cmk_auto_rotate_status[user_name] == true) {
        pid_t pid = cmk_auto_rotate_pids[user_name];
        kill(pid, SIGTERM);
        std::cout << "The background process for CMK_auto_rotate (PID: " << pid << ", User: " << user_name << ") stops."  << std::endl;
    }
    //删除当前用户的cmk自动轮转状态
    cmk_auto_rotate_status.erase(user_name);
    saveAutoRotateStatus();
    save();
    return true;
}

bool LocalKmsCore::describeCmk(const std::string &user_name, std::string &result, bool decrypt) {
    json cmk_info;
    if (!hasCmk(user_name)) {
        return false;
    }

    int key_id = _data["index"][user_name];
    if (!_data["cmk"].contains(std::to_string(key_id))) {
        return false;
    }

    cmk_info = _data["cmk"][std::to_string(key_id)];

    if (decrypt) {
        std::string cmk_data = cmk_info["cmk_data"];
        decryptKey(cmk_data);
        cmk_info["cmk_data_plain"] = cmk_data;
    }

    // 修正字段名和转义单引号
    std::string cmk_data = decrypt ? cmk_info["cmk_data_plain"] : cmk_info["cmk_data"];
    cmk_data = std::regex_replace(cmk_data, std::regex("'"), "''"); // 转义单引号
    int rotate_period = cmk_info.value("rotate_period", 0);
    bool is_primary = cmk_info.value("is_primary_version", false);
    bool is_rotated = cmk_info.value("is_rotated", false);

    result = "SELECT '" +
            std::string(user_name) + "' AS username, '" +
            cmk_data + "' AS CMK_data, " +
            std::to_string(rotate_period) + " AS rotate_period, " +
            (is_primary ? "true" : "false") + " AS is_primary_version, " +
            (is_rotated ? "true" : "false") + " AS is_rotated;";

    return true;
}


bool LocalKmsCore::encryptData(std::string &ori_key) {
    constexpr int key_size = 16;
    std::string string_key = _cmk;
    unsigned char key[key_size] = {0};
    for (size_t i = 0; i < 15; i++) {
        key[i] = static_cast<unsigned char>(string_key[i]);
    }
    int ori_key_len = ori_key.size();
    int block_size = AES_BLOCK_SIZE;
    AES_KEY encrypt_key;
    if (ori_key_len % block_size != 0) {
        int padding_len = block_size - (ori_key_len % block_size);
        ori_key.append(padding_len, '\0');  // 填充ori_key
    }
    if (AES_set_encrypt_key(key, 128, &encrypt_key) < 0) {
        std::cerr << "Failed to set AES encryption key!" << std::endl;
        return false;
    }
    std::string encrypted(ori_key.size(), '\0');
    unsigned char *input_data = reinterpret_cast<unsigned char *>(&ori_key[0]);
    unsigned char *output_data = reinterpret_cast<unsigned char *>(&encrypted[0]);

    for (size_t i = 0; i < ori_key.size(); i += block_size) {
        AES_ecb_encrypt(input_data + i, output_data + i, &encrypt_key, AES_ENCRYPT);
    }
    //为了实现存储json改为base64编码，KeyStruct _struct编码结构是否需要修改？
    std::string base64_encrypted = base64_encode(reinterpret_cast<const unsigned char *>(encrypted.c_str()),
                                                 encrypted.size());
    ori_key = base64_encrypted;

    return true;
}

bool LocalKmsCore::decryptData(std::string &ori_key) {
    constexpr int key_size = 16;
    std::string string_key = _cmk;
    unsigned char key[key_size] = {0};
    for (size_t i = 0; i < 15; i++) {
        key[i] = static_cast<unsigned char>(string_key[i]);
    }
    int ori_key_len = ori_key.size();
    int block_size = AES_BLOCK_SIZE;
    std::string decoded = base64_decode(ori_key);
    AES_KEY decrypt_key;
    if (AES_set_decrypt_key(key, 128, &decrypt_key) < 0) {
        std::cerr << "Failed to set AES decryption key!" << std::endl;
        return false;
    }
    std::string decrypted(decoded.size(), '\0');
    unsigned char *input_data = reinterpret_cast<unsigned char *>(&decoded[0]);
    unsigned char *output_data = reinterpret_cast<unsigned char *>(&decrypted[0]);

    for (size_t i = 0; i + block_size <= decoded.size(); i += block_size) {
        AES_ecb_encrypt(input_data + i, output_data + i, &decrypt_key, AES_DECRYPT);
    }
    // 去除填充的\0
    size_t last_non_null_pos = decrypted.find_last_not_of('\0');
    if (last_non_null_pos != std::string::npos) {
        decrypted.erase(last_non_null_pos + 1);  // 删除从最后一个非零字符后的所有填充字符
    }
    ori_key = decrypted;
    return true;

}

//手动轮转函数
bool LocalKmsCore::rotateCmkNow(const std::string &user_name) {
    if (!hasCmk(user_name)) {
        std::cerr << "No CMK found for user: " << user_name << std::endl;
        return false;
    }

    //获取old_cmk信息
    int old_cmk_id = _data["index"][user_name];
    json old_cmk = _data["cmk"][std::to_string(old_cmk_id)];
    int rotate_period = old_cmk["rotate_period"];
    std::string old_cmk_data = old_cmk["cmk_data"];

    //解密old_cmk
    decryptKey(old_cmk_data);

    //取DEK信息并解密
    bool hasDEK = false;
    //检查是否有DEK
    std::map<std::string, std::string> _dek_tmp;
    connectionRotationSelectDek(user_name, _dek_tmp, hasDEK);


    //修改旧cmk信息
    old_cmk["is_rotated"] = true;
    old_cmk["is_primary_version"] = false;

    //保存修改后信息
    _data["cmk"][std::to_string(old_cmk_id)] = old_cmk;

    //创建新cmk
    // CMK new_cmk;
    if (createCmk(user_name, rotate_period)) {
        if (hasDEK) {
            //重加密DEK
            // _cmk = new_cmk._cmk_data;
            connectionRotationUpdataDek(user_name, _dek_tmp);  
        } else {
            std::cout << "The user has no DEK now, skipping DEK update." << std::endl;
        }
          
        // new_cmk._next_rotate_time = now + 30 * 24 * 60 * 60; // 30天后
        // storeCmk(new_cmk, true);
        return true;
    }
    return false;
}


//处理自动轮转命令
bool LocalKmsCore::handleAutoRotateCmd(std::string *auto_rotate_action, const std::string &user_name) {
    std::string action = auto_rotate_action->c_str();
    //开启自动轮转
    if (action == "on") {
        // 检查是否已经存在自动轮转进程
        if (cmk_auto_rotate_status[user_name] == true) {
            std::cout << "CMK_auto_rotate is already enabled for user: " << user_name << std::endl;
            return true;
        }

        // 创建新的后台进程
        pid_t pid = fork();
        if (pid == 0) {
            // 子进程
            setsid();//脱离终端控制
            std::cout << "The background process for CMK_auto_rotate starts, and the PID is " << getpid() << "." << std::endl;
            autoRotateProcess(user_name);
            exit(0);
            return true;
        } else if (pid > 0) {
            // 父进程
            cmk_auto_rotate_pids[user_name] = pid;
            cmk_auto_rotate_status[user_name] = true;
            saveAutoRotateStatus();//保存状态
            std::cout << "CMK_auto_rotate enabled for user: " << user_name << std::endl;
            return true;
        } else {
            std::cerr << "Failed to create CMK_auto_rotate process for user: " << user_name << std::endl;
            return false;
        }
    } 
    //关闭自动轮转
    else if (action == "off") {
        // 关闭自动轮转进程
        if (cmk_auto_rotate_status[user_name] == true) {
            pid_t pid = cmk_auto_rotate_pids[user_name];
            if (kill(pid, SIGTERM) == 0) {
                cmk_auto_rotate_status[user_name] = false;
                saveAutoRotateStatus();
                std::cout << "The background process for CMK_auto_rotate (PID: " << pid << ") stops."  << std::endl;
                std::cout << "CMK_auto_rotate is disabled now for user: " << user_name << std::endl;
                return true;
            } else {
                std::cerr << "Failed to terminate CMK_auto-rotate process for user: " << user_name << std::endl;
                return false;
            }
        } 
        //还未开启过或已关闭自动轮转进程
        else {
            std::cout << "CMK_auto_rotate is already disabled for user: " << user_name << std::endl;
            return true;
        }
    } 
    // 查询自动轮转状态
    else if (action == "status") {
        if (cmk_auto_rotate_status[user_name] == true) {
            std::cout << "CMK_auto_rotate is enabled for user: " << user_name << std::endl;
        } else {
            std::cout << "CMK_auto_rotate is disabled for user: " << user_name << std::endl;
        }
        return true;
    }
    else {
        std::cerr << "Invalid operation for CMK_auto_rotate command." << std::endl;
        return false;
    }
}

//根据用户名获取CMK自动轮转状态
bool LocalKmsCore::getCmkAutoRotateStatusByUsername(const std::string &user_name) {
    if (user_name.empty()) {
        return false;
    }
    if (!hasCmk(user_name)) {
        return false;
    }
    return cmk_auto_rotate_status[user_name];
}

bool LocalKmsCore::createDek(std::string &col_dek, const std::string &column_name) {
    col_dek.clear();
    return createDerivedDek(col_dek, column_name);
}


//轮转后从表中取出DEK并解密
void connectionRotationSelectDek(const std::string &user_name, std::map<std::string, std::string> &_dek_tmp, bool &hasDEK) {
    const char *conninfo1 = "dbname=dekmaster user=dekmaster password=secure_password hostaddr=127.0.0.1 port=5432";
    PGconn *conn1 = PQconnectdb(conninfo1);
    if (PQstatus(conn1) != CONNECTION_OK) {
        fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn1));
        PQfinish(conn1);
    }
    // 执行查询
    std::string query1 = "SELECT t, c, dek FROM dek_store WHERE username = '" + user_name + "';";
    PGresult *res1 = PQexec(conn1, query1.c_str());
    // 检查查询状态
    if (PQresultStatus(res1) != PGRES_TUPLES_OK) {
        fprintf(stderr, "Query execution failed: %s\n", PQerrorMessage(conn1));
        PQclear(res1);
        PQfinish(conn1);
    }

    int nrows = PQntuples(res1);  // 获取查询结果的行数

    for (int i = 0; i < nrows; i++) { // 遍历每一行
        std::string table_name(PQgetvalue(res1, i, 0));  //表名
        std::string col_name = PQgetisnull(res1, i, 1) ? "" : PQgetvalue(res1, i, 1);  //列名
        std::string dek(PQgetvalue(res1, i, 2));        //密文dek
        
        KMSInterface::decryptData(dek);     //解密dek
        
        // 使用表名和列名组合作为键
        std::string key = table_name + (col_name.empty() ? "" : ":" + col_name);
        _dek_tmp[key] = dek;              //将解密dek信息和表名映射关系存入临时结构
        std::cout << "Table: " << table_name << ", Column: " << (col_name.empty() ? "TABLE_KEY" : col_name) 
                 << ", Decrypted DEK: " << dek << std::endl;
    }
    
    if (!_dek_tmp.empty()) {
        hasDEK = true;
    }
           
    PQclear(res1);   // 释放查询结果
    PQfinish(conn1); // 关闭数据库连接
}

//轮转后完成DEK重加密并更新存储
void connectionRotationUpdataDek(const std::string &user_name, std::map<std::string, std::string> &_dek_tmp) {
    const char *conninfo1 = "dbname=dekmaster user=dekmaster password=secure_password hostaddr=127.0.0.1 port=5432";
    PGconn *conn1 = PQconnectdb(conninfo1);
    if (PQstatus(conn1) != CONNECTION_OK) {
        fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn1));
        PQfinish(conn1);
    }

    // 遍历临时存储结构，重加密dek
    for (auto &entry : _dek_tmp) {
        std::string key = entry.first;
        std::string dek = entry.second;
        
        // 解析key获取表名和列名
        size_t pos = key.find(":");
        std::string table_name = pos == std::string::npos ? key : key.substr(0, pos);
        std::string col_name = pos == std::string::npos ? "" : key.substr(pos + 1);

        //重加密
        KMSInterface::encryptData(dek);

        //更新数据库
        std::string update_query;
        if(col_name.empty()) {
            update_query = "UPDATE dek_store SET dek = '" + dek + "' WHERE username = '" + user_name + 
                         "' AND t = '" + table_name + "' AND c IS NULL;";
        } else {
            update_query = "UPDATE dek_store SET dek = '" + dek + "' WHERE username = '" + user_name + 
                         "' AND t = '" + table_name + "' AND c = '" + col_name + "';";
        }
        
        PGresult *res = PQexec(conn1, update_query.c_str());

        if (PQresultStatus(res) != PGRES_COMMAND_OK) {
            fprintf(stderr, "Update execution failed: %s\n", PQerrorMessage(conn1));
            PQclear(res);
        } else {
            PQclear(res);
        }
    }
    std::cout << "Successfully update all DEKs of \"" << user_name << "\"." << std::endl;
    PQfinish(conn1);
}