// ============================================================================
// btc_1m_kline_sub_probe.cpp (Rev-2: r2-65667 — CEF/Zero-Thread SIGABRT-Hardened)
// Minimal In-Process Single-Symbol (BTC sid=12000015) 1m K-Line Subscription Probe
//
// Verified against FTNN Desktop 16.39.27508 x86-64 ELF binaries:
//   - libCoreBiz.so : IFTChannelProxy::SendCommand @ 0x1dc0c0
//   - libQotBase.so : INNBiz_Qot_PushQot::ms_pImpl @ 0x81d280,
//                     NNBiz_Qot_PushQot::SubOrUnSub @ 0x3ead00 (...RK12NN_Prob2Item),
//                     NNBiz_Qot_PushQot::DoSendSubReq @ 0x3f16f0 (cmd_id=0x1843=6211),
//                     INNBiz_Qot_PushQot::RegisterCallBack @ 0x3d09a0 (push=0x1844=6212),
//                     INNProtoCenter::OnPushKline @ 0x3d1760 (StockKline, mt=6 fields 6/10),
//                     IStockListData::GetStocksByFutuSymbol @ 0x4daa10,
//                     IStockUtil::GetCSMktType @ 0x5736c0
//   - libf3cchart.so: CSecurityKlineService::SendPage @ 0x66b24f (KlineReq=0x1811=6161, mt=4 fields 7/12)
//
// Rev-2 SIGABRT Hardening (Addresses 65664 / 65665 / 65667):
//   1. CEF Child-Process Guard: Reads /proc/self/cmdline in constructor; immediately
//      no-ops if "--type=" is present (Chromium zygote/renderer/gpu/utility), and
//      strips self from LD_PRELOAD so forked CEF sandbox children never load the probe
//      (prevents Chromium AssertSingleThreaded() / seccomp-bpf CHECK() -> SIGABRT).
//   2. Zero Background Threads + Same-Thread Piggyback: Spawns ZERO std::thread in
//      constructor. Intercepts IFTChannelProxy::SendCommand via RTLD_NEXT and triggers
//      BTC 1m SubOrUnSub (0x1843) + 1m KlineReq pull (0x1811) on FTNN's own business
//      thread once CSChannelType==1 quote traffic is live (100% Qt QObject thread-safe).
//   3. Async-Signal-Safe SIGABRT Backtrace Logger: Captures raw stack frames + /proc/self/maps
//      to /tmp/btc_1m_sigabrt_bt.log if SIGABRT fires anywhere in the process.
//   4. Pre-bound Live BTC sid=12000015 (override via BTC_SEC_ID=<uint64>).
//
// Build:
//   g++ -shared -fPIC -O2 -std=c++17 -Wall -Wextra -Werror btc_1m_kline_sub_probe.cpp -o libbtc_1m_sub_probe.so -ldl -lpthread
// ============================================================================

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#include <atomic>
#include <chrono>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <dlfcn.h>
#include <execinfo.h>
#include <fcntl.h>
#include <functional>
#include <mutex>
#include <optional>
#include <set>
#include <string>
#include <unistd.h>
#include <vector>

namespace {

enum CSChannelType   : uint32_t { CS_CHANNEL_QUOTE = 1 };
enum CSProtoError    : uint32_t { CS_PROTO_OK = 0 };
enum CSBrokerId      : uint32_t {};
enum NN_QotSubBit    : uint32_t { QOT_SUB_BIT_CUSTOM_KLINE = 10001 };
enum NN_SubscribeBit : uint32_t {};
enum NN_CSMktType    : uint32_t {};

struct CSProtoData {
    uint16_t cmd_id;              // +0x00 (0x1843=6211 SubSetReq, 0x1811=6161 KlineReq)
    uint16_t _pad[3];             // +0x02..+0x07
    std::string payload;          // +0x08..+0x27 (32B libstdc++ SSO basic_string)
};
static_assert(sizeof(CSProtoData) == 40, "CSProtoData ABI mismatch");

struct CSRequestExt {
    uint16_t timeout_ms = 10000;  // +0x00 (0x2710 in DoSendSubReq)
    uint16_t _pad0[3] = {0, 0, 0};
    std::string ext_head;         // +0x08..+0x27 (2B {(uint8_t)mktType, 0x00} required for 0x1843!)
    uint64_t* opt_seq_ptr = nullptr; // +0x28
    uint32_t flags = 0;           // +0x30
    uint32_t _pad1 = 0;           // +0x34
};
static_assert(sizeof(CSRequestExt) == 56, "CSRequestExt ABI mismatch");

struct CSResponseExt;
class QObject;

struct NN_Prob2SubItem {
    uint32_t order_type = 0;
    uint32_t order_level = 0;
    bool operator<(const NN_Prob2SubItem& o) const {
        return order_type != o.order_type ? order_type < o.order_type : order_level < o.order_level;
    }
};

struct NN_KlineProb2SubItem {
    uint32_t exright_type = 0;            // node+0x20: EXRIGHT_TYPE_NONE = 0
    uint32_t base_type = 2;               // node+0x24: BASE_KLINE_MINUTE = 2
    uint32_t custom_number = 1;           // node+0x28: 1 (1-minute K-line)
    uint32_t _pad0 = 0;                   // node+0x2c
    std::vector<uint32_t> section_type;   // node+0x30..+0x47 (24B)
    uint32_t subscribe_type = 0;          // node+0x48: SUBSCRIBE_TYPE_KLINE = 0
    uint32_t _pad1 = 0;                   // node+0x4c

    bool operator<(const NN_KlineProb2SubItem& o) const {
        if (exright_type != o.exright_type) return exright_type < o.exright_type;
        if (base_type != o.base_type) return base_type < o.base_type;
        if (custom_number != o.custom_number) return custom_number < o.custom_number;
        if (section_type != o.section_type) return section_type < o.section_type;
        return subscribe_type < o.subscribe_type;
    }
};
static_assert(sizeof(NN_KlineProb2SubItem) == 48, "NN_KlineProb2SubItem size mismatch");

struct NN_Prob2Item {
    std::set<NN_Prob2SubItem>      lv2_items;   // +0x00..+0x2f (48B)
    std::set<NN_KlineProb2SubItem> kline_items; // +0x30..+0x5f (48B)
};
static_assert(sizeof(NN_Prob2Item) == 96, "NN_Prob2Item ABI mismatch");

// ---- Process-role & state flags ----
bool g_is_cef_child = false;
bool g_passive_only = false;
std::atomic<bool> g_sub_triggered{false};
std::atomic<bool> g_in_probe_send{false};
int64_t g_boot_mono_ms = 0;
int64_t g_min_wait_ms  = 0;

int64_t now_mono_ms() {
    return std::chrono::duration_cast<std::chrono::milliseconds>(
        std::chrono::steady_clock::now().time_since_epoch()).count();
}

// ---- Raw POSIX JSONL logger (immune to FTNN freopen("/dev/null") on stdout/stderr) ----
std::mutex g_log_mu;
int g_log_fd = -1;

void tap_log(const char* json_line) {
    if (g_is_cef_child) return;
    std::lock_guard<std::mutex> lk(g_log_mu);
    if (g_log_fd < 0) {
        const char* p = std::getenv("BTC_SUB_LOG");
        if (!p || !*p) p = "/tmp/btc_1m_kline_tap.jsonl";
        g_log_fd = ::open(p, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
    }
    if (g_log_fd >= 0) {
        size_t n = std::strlen(json_line);
        (void)::write(g_log_fd, json_line, n);
        (void)::write(g_log_fd, "\n", 1);
    }
}

// ---- Async-signal-safe SIGABRT diagnostic backtrace writer (for 65665) ----
struct sigaction g_prev_abrt{};

void sigabrt_bt_handler(int sig, siginfo_t* info, void* uctx) {
    const char* bt_path = std::getenv("BTC_ABRT_LOG");
    if (!bt_path || !*bt_path) bt_path = "/tmp/btc_1m_sigabrt_bt.log";
    int fd = ::open(bt_path, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
    if (fd >= 0) {
        const char hdr[] = "=== SIGABRT CAPTURED BY libbtc_1m_sub_probe ===\n";
        (void)::write(fd, hdr, sizeof(hdr) - 1);
        void* frames[48];
        int n = ::backtrace(frames, 48);
        if (n > 0) {
            ::backtrace_symbols_fd(frames, n, fd);
        }
        int mfd = ::open("/proc/self/maps", O_RDONLY | O_CLOEXEC);
        if (mfd >= 0) {
            const char mhdr[] = "\n--- /proc/self/maps ---\n";
            (void)::write(fd, mhdr, sizeof(mhdr) - 1);
            char buf[4096];
            ssize_t r;
            size_t total = 0;
            while ((r = ::read(mfd, buf, sizeof(buf))) > 0 && total < 262144) {
                (void)::write(fd, buf, static_cast<size_t>(r));
                total += static_cast<size_t>(r);
            }
            ::close(mfd);
        }
        ::close(fd);
    }
    if ((g_prev_abrt.sa_flags & SA_SIGINFO) && g_prev_abrt.sa_sigaction) {
        g_prev_abrt.sa_sigaction(sig, info, uctx);
        return;
    }
    if (g_prev_abrt.sa_handler != SIG_DFL && g_prev_abrt.sa_handler != SIG_IGN && g_prev_abrt.sa_handler != nullptr) {
        g_prev_abrt.sa_handler(sig);
        return;
    }
    std::signal(SIGABRT, SIG_DFL);
    ::raise(SIGABRT);
}

// ---- Minimal dependency-free Protobuf wire helpers ----
void pb_write_varint(std::string& out, uint64_t v) {
    while (v >= 0x80) {
        out.push_back(static_cast<char>((v & 0x7F) | 0x80));
        v >>= 7;
    }
    out.push_back(static_cast<char>(v));
}

void pb_write_tag(std::string& out, uint32_t field_no, uint32_t wire_type) {
    pb_write_varint(out, (static_cast<uint64_t>(field_no) << 3) | wire_type);
}

void pb_write_bytes(std::string& out, uint32_t field_no, const std::string& bytes) {
    pb_write_tag(out, field_no, 2);
    pb_write_varint(out, bytes.size());
    out.append(bytes);
}

bool pb_read_varint(const uint8_t* buf, size_t len, size_t& i, uint64_t& out) {
    out = 0;
    unsigned shift = 0;
    while (i < len && shift < 64) {
        uint8_t b = buf[i++];
        out |= static_cast<uint64_t>(b & 0x7F) << shift;
        if ((b & 0x80) == 0) return true;
        shift += 7;
    }
    return false;
}

int64_t as_int64(uint64_t u) {
    int64_t s;
    std::memcpy(&s, &u, sizeof(s));
    return s;
}

std::string encode_1m_kline_sub_prob() {
    std::string kt_v2;
    pb_write_tag(kt_v2, 1, 0); pb_write_varint(kt_v2, 2); // BASE_KLINE_MINUTE = 2
    pb_write_tag(kt_v2, 2, 0); pb_write_varint(kt_v2, 1); // custom_number = 1

    std::string sub_item;
    pb_write_tag(sub_item, 1, 0); pb_write_varint(sub_item, 0); // exright_type = 0
    pb_write_bytes(sub_item, 2, kt_v2);
    pb_write_tag(sub_item, 4, 0); pb_write_varint(sub_item, 0); // SUBSCRIBE_TYPE_KLINE = 0

    std::string sub_prob;
    pb_write_bytes(sub_prob, 1, sub_item);
    return sub_prob;
}

std::string encode_1m_subscribe_set_req(uint64_t sec_id, std::optional<CSBrokerId> broker_id) {
    std::string prob2 = encode_1m_kline_sub_prob();

    std::string bit_info;
    pb_write_tag(bit_info, 1, 0); pb_write_varint(bit_info, 10001); // SBIT_CUSTOM_KLINE = 10001
    pb_write_bytes(bit_info, 3, prob2);

    std::string sec_sub;
    pb_write_tag(sec_sub, 1, 0); pb_write_varint(sec_sub, sec_id);
    pb_write_bytes(sec_sub, 2, bit_info);
    if (broker_id.has_value()) {
        pb_write_tag(sec_sub, 3, 0);
        pb_write_varint(sec_sub, static_cast<uint64_t>(static_cast<int64_t>(static_cast<uint32_t>(*broker_id))));
    }

    std::string set_req;
    pb_write_bytes(set_req, 1, sec_sub);
    return set_req;
}

std::string encode_1m_kline_pull_req(uint64_t sec_id, uint32_t count, std::optional<CSBrokerId> broker_id) {
    std::string kt_v2;
    pb_write_tag(kt_v2, 1, 0); pb_write_varint(kt_v2, 2);
    pb_write_tag(kt_v2, 2, 0); pb_write_varint(kt_v2, 1);

    uint64_t now_s = static_cast<uint64_t>(
        std::chrono::duration_cast<std::chrono::seconds>(
            std::chrono::system_clock::now().time_since_epoch()).count()) + 120;

    std::string req;
    pb_write_tag(req, 1, 0);  pb_write_varint(req, sec_id); // security_id (BTC=12000015)
    pb_write_tag(req, 2, 0);  pb_write_varint(req, 1);      // KLINE_1MINUTE = 1
    pb_write_tag(req, 3, 0);  pb_write_varint(req, 0);      // EXRIGHT_TYPE_NONE = 0
    pb_write_tag(req, 4, 0);  pb_write_varint(req, 0);      // DATA_SET_TYPE_KLINE = 0
    pb_write_tag(req, 5, 0);  pb_write_varint(req, 3);      // DATA_RANGE_END_TIME_ITEM_COUNT = 3
    pb_write_tag(req, 7, 0);  pb_write_varint(req, now_s);
    pb_write_tag(req, 8, 0);  pb_write_varint(req, count);
    if (broker_id.has_value()) {
        pb_write_tag(req, 11, 0);
        pb_write_varint(req, static_cast<uint64_t>(static_cast<int64_t>(static_cast<uint32_t>(*broker_id))));
    }
    pb_write_bytes(req, 12, kt_v2);
    return req;
}

void decode_and_log_stock_kline(const char* src, uint64_t sec_id_hint, uint32_t bit, const std::string& raw) {
    const auto* buf = reinterpret_cast<const uint8_t*>(raw.data());
    size_t i = 0, n = raw.size();
    uint64_t sec_id = sec_id_hint;
    size_t bars = 0;

    while (i < n) {
        uint64_t tag = 0;
        if (!pb_read_varint(buf, n, i, tag)) break;
        uint32_t fn = static_cast<uint32_t>(tag >> 3);
        uint32_t wt = static_cast<uint32_t>(tag & 7);
        if (wt == 0) {
            uint64_t v = 0;
            if (!pb_read_varint(buf, n, i, v)) break;
            if (fn == 1 && sec_id == 0) sec_id = v;
        } else if (wt == 2) {
            uint64_t ln = 0;
            if (!pb_read_varint(buf, n, i, ln) || i + ln > n) break;
            if (fn == 6 || fn == 7) { // StockKline(mt=6): field 6; KlineRsp(mt=4): field 7
                size_t j = i, end = i + ln;
                uint64_t ts = 0, vol = 0, turn = 0;
                int64_t o = 0, h = 0, l = 0, c = 0;
                std::string hp_vol, hp_turn;
                while (j < end) {
                    uint64_t itag = 0;
                    if (!pb_read_varint(buf, end, j, itag)) break;
                    uint32_t ifn = static_cast<uint32_t>(itag >> 3);
                    uint32_t iwt = static_cast<uint32_t>(itag & 7);
                    if (iwt == 0) {
                        uint64_t iv = 0;
                        if (!pb_read_varint(buf, end, j, iv)) break;
                        switch (ifn) {
                            case 1: ts = iv; break;
                            case 3: c = as_int64(iv); break;
                            case 4: o = as_int64(iv); break;
                            case 5: h = as_int64(iv); break;
                            case 6: l = as_int64(iv); break;
                            case 7: vol = iv; break;
                            case 8: turn = iv; break;
                            default: break;
                        }
                    } else if (iwt == 2) {
                        uint64_t iln = 0;
                        if (!pb_read_varint(buf, end, j, iln) || j + iln > end) break;
                        if (ifn == 24) hp_vol.assign(reinterpret_cast<const char*>(buf + j), iln);
                        if (ifn == 25) hp_turn.assign(reinterpret_cast<const char*>(buf + j), iln);
                        j += iln;
                    } else if (iwt == 1) {
                        j += 8;
                    } else if (iwt == 5) {
                        j += 4;
                    } else {
                        break;
                    }
                }
                if (ts > 0) {
                    ++bars;
                    char line[704];
                    std::snprintf(
                        line, sizeof(line),
                        "{\"ev\":\"%s\",\"sec_id\":%llu,\"bit\":%u,\"ts\":%llu,"
                        "\"o\":%lld,\"h\":%lld,\"l\":%lld,\"c\":%lld,"
                        "\"vol\":%llu,\"turn\":%llu,\"hp_vol\":\"%s\",\"hp_turn\":\"%s\"}",
                        src,
                        static_cast<unsigned long long>(sec_id),
                        bit,
                        static_cast<unsigned long long>(ts),
                        static_cast<long long>(o),
                        static_cast<long long>(h),
                        static_cast<long long>(l),
                        static_cast<long long>(c),
                        static_cast<unsigned long long>(vol),
                        static_cast<unsigned long long>(turn),
                        hp_vol.c_str(),
                        hp_turn.c_str()
                    );
                    tap_log(line);
                }
            }
            i += ln;
        } else if (wt == 1) {
            i += 8;
        } else if (wt == 5) {
            i += 4;
        } else {
            break;
        }
    }
    if (bars == 0) {
        char line[256];
        std::snprintf(line, sizeof(line),
            "{\"ev\":\"%s_raw\",\"sec_id\":%llu,\"bit\":%u,\"bytes\":%zu}",
            src, static_cast<unsigned long long>(sec_id), bit, raw.size());
        tap_log(line);
    }
}

using OnPushKlineFn = void (*)(unsigned long, std::optional<CSBrokerId>, NN_SubscribeBit, const std::string&);
using SendCommandFn = unsigned long (*)(
    CSChannelType, const CSProtoData&, const CSRequestExt*,
    std::function<void(unsigned long, CSProtoE