#include "okx_client.hpp"
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <netdb.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstring>
#include <vector>

namespace quant {

// ---------- 带签名 header 的 HTTP POST(复用 OpenSSL TLS,支持自定义 header) ----------
std::string OkxExchange::https_request(const std::string& url, const std::string& method,
                                       const std::vector<std::pair<std::string, std::string>>& headers,
                                       const std::string& body) {
    // 解析 host/port/path
    std::string host, port = "443", path;
    std::string rest = url.substr(url.find("://") + 3);
    size_t slash = rest.find('/');
    std::string authority = (slash == std::string::npos) ? rest : rest.substr(0, slash);
    path = (slash == std::string::npos) ? "/" : rest.substr(slash);
    size_t colon = authority.rfind(':');
    if (colon != std::string::npos) { host = authority.substr(0, colon); port = authority.substr(colon + 1); }
    else host = authority;

    // TCP + TLS
    struct addrinfo hints{}, *res = nullptr;
    hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM;
    if (getaddrinfo(host.c_str(), port.c_str(), &hints, &res) != 0 || !res) return "";
    int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if (fd < 0) { freeaddrinfo(res); return ""; }
    struct timeval tv{15, 0};
    setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
    if (::connect(fd, res->ai_addr, res->ai_addrlen) != 0) { ::close(fd); freeaddrinfo(res); return ""; }
    freeaddrinfo(res);

    SSL_library_init();
    SSL_CTX* ctx = SSL_CTX_new(TLS_client_method());
    SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, nullptr);
    SSL* ssl = SSL_new(ctx);
    SSL_set_fd(ssl, fd);
    SSL_set_tlsext_host_name(ssl, host.c_str());
    if (SSL_connect(ssl) != 1) { SSL_free(ssl); SSL_CTX_free(ctx); ::close(fd); return ""; }

    // 请求
    std::string req = method + " " + path + " HTTP/1.1\r\nHost: " + host + "\r\n";
    for (const auto& [k, v] : headers) req += k + ": " + v + "\r\n";
    if (!body.empty()) req += "Content-Length: " + std::to_string(body.size()) + "\r\n";
    req += "Connection: close\r\n\r\n";
    if (!body.empty()) req += body;
    SSL_write(ssl, req.data(), (int)req.size());

    // 响应
    std::string resp;
    char buf[8192];
    int n;
    while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) resp.append(buf, (size_t)n);
    SSL_free(ssl); SSL_CTX_free(ctx); ::close(fd);

    // 分离 header/body + chunked 解码
    size_t hdr_end = resp.find("\r\n\r\n");
    if (hdr_end == std::string::npos) return "";
    std::string header = resp.substr(0, hdr_end);
    std::string body_resp = resp.substr(hdr_end + 4);
    if (header.find("chunked") != std::string::npos) {
        std::string dec;
        size_t pos = 0;
        while (pos < body_resp.size()) {
            size_t le = body_resp.find("\r\n", pos);
            if (le == std::string::npos) break;
            unsigned long sz = std::stoul(body_resp.substr(pos, le - pos), nullptr, 16);
            if (sz == 0) break;
            pos = le + 2;
            if (pos + sz <= body_resp.size()) { dec.append(body_resp, pos, sz); pos += sz; }
            if (pos + 1 < body_resp.size() && body_resp[pos] == '\r') pos += 2;
        }
        body_resp = dec;
    }
    return body_resp;
}

// 真实下单(demo 模式):POST /api/v5/trade/order
OrderResult OkxExchange::place_order(const OrderRequest& req, double sz) {
    OrderResult r;
    std::string body = "{\"instId\":\"" + cfg_.inst_id + "\","
                       "\"tdMode\":\"cross\","
                       "\"side\":\"" + std::string(req.side == 0 ? "buy" : "sell") + "\","
                       "\"ordType\":\"" + std::string(req.type == 0 ? "market" : "limit") + "\","
                       "\"sz\":\"" + std::to_string(sz) + "\"";
    if (req.type == 1) body += ",\"px\":\"" + std::to_string(req.price) + "\"";
    body += "}";

    std::string path = "/api/v5/trade/order";
    std::string ts = timestamp_now();
    std::string sig = sign(cfg_.secret, ts, "POST", path, body);

    std::vector<std::pair<std::string, std::string>> headers = {
        {"Content-Type", "application/json"},
        {"OK-ACCESS-KEY", cfg_.api_key},
        {"OK-ACCESS-SIGN", sig},
        {"OK-ACCESS-TIMESTAMP", ts},
        {"OK-ACCESS-PASSPHRASE", cfg_.passphrase},
    };
    if (cfg_.demo) headers.emplace_back("x-simulated-trading", "1");  // demo 模式

    std::string resp = https_request(cfg_.base_url + path, "POST", headers, body);
    // 解析 {"code":"0","data":[{"ordId":"...","sCode":"0"}],"msg":""}
    size_t p = resp.find("\"ordId\":\"");
    if (p == std::string::npos) { r.error = resp.empty() ? "empty response" : resp.substr(0, 200); return r; }
    p += 10;
    size_t end = resp.find('"', p);
    r.order_id = std::stoull(resp.substr(p, end - p));
    r.ok = true;
    return r;
}

// 查询余额(demo):GET /api/v5/account/balance -> data[0].totalEq(USD 等值)
double OkxExchange::get_balance_usd() {
    std::string path = "/api/v5/account/balance";
    std::string ts = timestamp_now();
    std::string sig = sign(cfg_.secret, ts, "GET", path, "");

    std::vector<std::pair<std::string, std::string>> headers = {
        {"OK-ACCESS-KEY", cfg_.api_key},
        {"OK-ACCESS-SIGN", sig},
        {"OK-ACCESS-TIMESTAMP", ts},
        {"OK-ACCESS-PASSPHRASE", cfg_.passphrase},
    };
    if (cfg_.demo) headers.emplace_back("x-simulated-trading", "1");

    std::string resp = https_request(cfg_.base_url + path, "GET", headers, "");
    size_t p = resp.find("\"totalEq\":\"");
    if (p == std::string::npos) return 0.0;
    p += 11;
    size_t end = resp.find('"', p);
    return std::strtod(resp.substr(p, end - p).c_str(), nullptr);
}

// 查询持仓:GET /api/v5/account/positions?instId=... -> data[].pos(正数多/负数空)
double OkxExchange::get_position(const Symbol& symbol) {
    std::string path = "/api/v5/account/positions?instId=" + cfg_.inst_id;
    std::string ts = timestamp_now();
    std::string sig = sign(cfg_.secret, ts, "GET", path, "");

    std::vector<std::pair<std::string, std::string>> headers = {
        {"OK-ACCESS-KEY", cfg_.api_key},
        {"OK-ACCESS-SIGN", sig},
        {"OK-ACCESS-TIMESTAMP", ts},
        {"OK-ACCESS-PASSPHRASE", cfg_.passphrase},
    };
    if (cfg_.demo) headers.emplace_back("x-simulated-trading", "1");

    std::string resp = https_request(cfg_.base_url + path, "GET", headers, "");
    size_t p = resp.find("\"pos\":\"");
    if (p == std::string::npos) return 0.0;
    p += 7;
    size_t end = resp.find('"', p);
    return std::strtod(resp.substr(p, end - p).c_str(), nullptr);
}

} // namespace quant