#include "device_sdk.h"
#include <sstream>
#include <iomanip>
#include <vector>

DeviceClient::DeviceClient(const std::string& base_url, const std::string& encrypt_key)
    : base_url_(base_url), encrypt_key_(encrypt_key) {
    curl_global_init(CURL_GLOBAL_ALL);
    curl_ = curl_easy_init();
}

DeviceClient::~DeviceClient() {
    if (curl_) {
        curl_easy_cleanup(curl_);
    }
    curl_global_cleanup();
}

bool DeviceClient::registerDevice(const DeviceInfo& device_info, std::string& error) {
    json request;
    request["uid"] = device_info.uid;
    request["device_model"] = device_info.device_model;
    if (!device_info.license_code.empty()) {
        request["license_code"] = device_info.license_code;
    }

    std::string response;
    if (!post(base_url_ + "/api/devices/register", request.dump(), response, error)) {
        return false;
    }

    auto resp_json = json::parse(response);
    if (resp_json["code"] != 0) {
        error = resp_json["error"];
        return false;
    }

    return true;
}

bool DeviceClient::validateDevice(const std::string& uid, ValidateResponse& response, std::string& error) {
    std::string encrypted_response;
    if (!get(base_url_ + "/api/devices/" + uid + "/validate", encrypted_response, error)) {
        return false;
    }

    auto resp_json = json::parse(encrypted_response);
    if (resp_json["code"] != 0) {
        error = resp_json["error"];
        return false;
    }

    std::string decrypted = decryptResponse(resp_json["data"]);
    auto data = json::parse(decrypted);
    
    response.status = data["status"];
    response.license_type = data["license_type"];
    response.expire_time = data["expire_time"];
    response.start_count = data["start_count"];
    response.max_uses = data["max_uses"];
    response.timestamp = data["timestamp"];

    return true;
}

bool DeviceClient::updateStartCount(const std::string& uid, int& count, std::string& error) {
    std::string response;
    if (!post(base_url_ + "/api/devices/" + uid + "/start", "", response, error)) {
        return false;
    }

    auto resp_json = json::parse(response);
    if (resp_json["code"] != 0) {
        error = resp_json["error"];
        return false;
    }

    count = resp_json["data"]["start_count"];
    return true;
}

bool DeviceClient::bindLicense(const std::string& uid, const std::string& license_code, std::string& error) {
    json request;
    request["license_code"] = license_code;

    std::string response;
    if (!post(base_url_ + "/api/devices/" + uid + "/license", request.dump(), response, error)) {
        return false;
    }

    auto resp_json = json::parse(response);
    if (resp_json["code"] != 0) {
        error = resp_json["error"];
        return false;
    }

    return true;
}

// ... HTTP 请求和加密相关的辅助函数实现 ... 