// ============================================================================
// btc_1m_kline_sub_probe.cpp
// Minimal In-Process Single-Symbol (BTC) 1m K-Line Subscription Probe for FTNN
// Verified against FTNN Desktop 16.39.27508 x86-64 ELF binaries:
//   - libCoreBiz.so : IFTChannelProxy::SendCommand @ 0x1dc0c0, FTChannelProxy::SendCommand @ 0x1d72b0
//   - libQotBase.so : INNBiz_Qot_PushQot::Sub @ 0x3d11f0, ms_pImpl @ 0x81d280,
//                     NNBiz_Qot_PushQot::SubOrUnSub @ 0x3ead00,
//                     NNBiz_Qot_PushQot::DoSendSubReq @ 0x3f16f0 (cmd_id=0x1843=6211),
//                     INNBiz_Qot_PushQot::RegisterCallBack @ 0x3d09a0 (push=0x1844=6212, resub=0x18a0=6304),
//                     INNProtoCenter::OnPushKline @ 0x3d1760,
//                     CQotSubBitMgr::GenerateProb2String @ 0x40eab0 (bit=0x2711=10001 -> KlineSubProb),
//                     IStockListData::GetStocksByFutuSymbol @ 0x4daa10,
//                     IStockUtil::GetCSMktType @ 0x5736c0
//   - libf3cchart.so: CSecurityKlineService::SendPage @ 0x66b24f (pull cmd_id=0x1811=6161)
//
// 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
//
// Runtime Note:
//   FTNN main() calls freopen("/dev/null", "w", stdout/stderr) (.rodata @ 0x4d030).
//   All telemetry writes via raw POSIX open()/write() to /tmp/btc_1m_kline_tap.jsonl
//   (override via env BTC_SUB_LOG=/path/to/log.jsonl).
// ============================================================================

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <dlfcn.h>
#include <fcntl.h>
#include <functional>
#include <mutex>
#include <optional>
#include <set>
#include <string>
#include <thread>
#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");

// Verified at FTChannelProxy::SendCommand (0x1d737f..0x1d73c6) & DoSendSubReq (0x3f1fae..0x3f2036)
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;

// Verified at NN_Prob2Item::~NN_Prob2Item (0x3abfa0) & GenerateProb2String (0x40eb10..0x40ef20)
struct NN_Prob2SubItem {
    uint32_t order_type = 0;      // node+0x20
    uint32_t order_level = 0;     // node+0x24
    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");

// ---- 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;
}

// Encode FTCmdKline.KlineSubProb for 1m K-line (base_type=2, custom_number=1, subscribe_type=0)
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_type = 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);                         // kline_type_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);                      // repeated sub_items = 1
    return sub_prob;
}

// Encode FTCmdStockQuoteSub.SubscribeSetReq (cmd_id = 0x1843 = 6211) for Route B wire fallback
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); // bit = SBIT_CUSTOM_KLINE (10001)
    pb_write_bytes(bit_info, 3, prob2);                             // prob2 = KlineSubProb

    std::string sec_sub;
    pb_write_tag(sec_sub, 1, 0); pb_write_varint(sec_sub, sec_id);  // security_id = 1
    pb_write_bytes(sec_sub, 2, bit_info);                           // repeated bit_info_list = 2
    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);                            // repeated security_list = 1
    return set_req;
}

// Encode FTCmdKline.KlineReq (cmd_id = 0x1811 = 6161) for latest N 1m bars
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 = 1
    pb_write_tag(req, 2, 0);  pb_write_varint(req, 1);      // kline_type = KLINE_1MINUTE (1)
    pb_write_tag(req, 3, 0);  pb_write_varint(req, 0);      // exright_type = 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_type = END_TIME_ITEM_COUNT (3)
    pb_write_tag(req, 7, 0);  pb_write_varint(req, now_s);  // end_time = 7
    pb_write_tag(req, 8, 0);  pb_write_varint(req, count);  // item_count = 8
    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);                         // kline_type_v2 = 12
    return req;
}

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

void tap_log(const char* json_line) {
    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);
    }
}

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.kline_item_list=6, KlineRsp.kline_item_list=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&);
OnPushKlineFn g_real_OnPushKline = nullptr;

} // namespace

// Intercept INNProtoCenter::OnPushKline (dispatched by NNBiz_Qot_PushQot::PushKline @ 0x3ed96f)
extern "C" void _ZN14INNProtoCenter11OnPushKlineEmSt8optionalI10CSBrokerIdE15NN_SubscribeBitRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE(
    unsigned long sec_id,
    std::optional<CSBrokerId> broker_id,
    NN_SubscribeBit bit,
    const std::string& data
) {
    decode_and_log_stock_kline("push_kline_0x1844", sec_id, static_cast<uint32_t>(bit), data);
    if (!g_real_OnPushKline) {
        g_real_OnPushKline = reinterpret_cast<OnPushKlineFn>(
            dlsym(RTLD_NEXT, "_ZN14INNProtoCenter11OnPushKlineEmSt8optionalI10CSBrokerIdE15NN_SubscribeBitRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE"));
    }
    if (g_real_OnPushKline) {
        g_real_OnPushKline(sec_id, broker_id, bit, data);
    }
}

namespace {

void worker_subscribe_btc_1m() {
    int wait_sec = 12;
    if (const char* w = std::getenv("BTC_SUB_DELAY_SEC")) {
        int v = std::atoi(w);
        if (v >= 1 && v <= 300) wait_sec = v;
    }
    std::this_thread::sleep_for(std::chrono::seconds(wait_sec));

    void* h_qot = dlopen("libQotBase.so", RTLD_LAZY | RTLD_NOLOAD);
    void* h_biz = dlopen("libCoreBiz.so", RTLD_LAZY | RTLD_NOLOAD);
    if (!h_qot || !h_biz) {
        tap_log("{\"ev\":\"probe_err\",\"msg\":\"libQotBase.so or libCoreBiz.so not loaded\"}");
        return;
    }

    using GetStocksBySymFn = std::vector<unsigned long> (*)(const std::string&);
    using GetCSMktTypeFn   = NN_CSMktType (*)(unsigned long);
    using GetEffBrokerFn   = std::optional<CSBrokerId> (*)(unsigned long, std::optional<CSBrokerId>);
    using SubOrUnSubFn     = bool (*)(void* self, bool is_sub, unsigned long handle,
                                      unsigned long sec_id, std::optional<CSBrokerId> broker_id,
                                      NN_QotSubBit bit, unsigned int prob_mask,
                                      const NN_Prob2Item& prob2);
    using SendCommandFn    = unsigned long (*)(CSChannelType, const CSProtoData&,
                                               const CSRequestExt*,
                                               std::function<void(unsigned long, CSProtoError, const CSProtoData&, const CSResponseExt*)>,
                                               QObject*);

    auto fn_get_stocks = reinterpret_cast<GetStocksBySymFn>(
        dlsym(h_qot, "_ZN14IStockListData21GetStocksByFutuSymbolERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE"));
    auto fn_get_mkt = reinterpret_cast<GetCSMktTypeFn>(
        dlsym(h_qot, "_ZN10IStockUtil12GetCSMktTypeEm"));
    auto fn_eff_broker = reinterpret_cast<GetEffBrokerFn>(
        dlsym(h_qot, "_ZN5quote13crypto_broker28GetEffectiveCryptoCSBrokerIDEmSt8optionalI10CSBrokerIdE"));
    auto pp_push_impl = reinterpret_cast<void**>(
        dlsym(h_qot, "_ZN18INNBiz_Qot_PushQot8ms_pImplE"));
    auto fn_sub_or_unsub = reinterpret_cast<SubOrUnSubFn>(
        dlsym(h_qot, "_ZN17NNBiz_Qot_PushQot10SubOrUnSubEbmmSt8optionalI10CSBrokerIdE12NN_QotSubBitjRK12NN_Prob2Item"));
    auto fn_send_cmd = reinterpret_cast<SendCommandFn>(
        dlsym(h_biz, "_ZN15IFTChannelProxy11SendCommandE13CSChannelTypeRK11CSProtoDataPK12CSRequestExtSt8functionIFvm12CSProtoErrorS3_PK13CSResponseExtEEP7QObject"));

    uint64_t btc_sec_id = 0;
    if (const char* env_id = std::getenv("BTC_SEC_ID"); env_id && *env_id) {
        btc_sec_id = std::strtoull(env_id, nullptr, 0);
    }
    if (btc_sec_id == 0 && fn_get_stocks) {
        for (const char* sym : {"BTCUSD", "BTC", "CC.BTCUSD", "CRYPTO.BTCUSD", "BTCUSDT"}) {
            auto ids = fn_get_stocks(std::string(sym));
            if (!ids.empty()) {
                btc_sec_id = ids.front();
                char buf[256];
                std::snprintf(buf, sizeof(buf),
                    "{\"ev\":\"resolved_symbol\",\"query\":\"%s\",\"sec_id\":%llu,\"candidates\":%zu}",
                    sym, static_cast<unsigned long long>(btc_sec_id), ids.size());
                tap_log(buf);
                break;
            }
        }
    }
    if (btc_sec_id == 0) {
        tap_log("{\"ev\":\"probe_wait_sec_id\",\"msg\":\"Set BTC_SEC_ID=<uint64> if symbol table not yet populated\"}");
        return;
    }

    NN_CSMktType mkt_type = fn_get_mkt ? fn_get_mkt(btc_sec_id) : static_cast<NN_CSMktType>(0);
    std::optional<CSBrokerId> broker_opt = std::nullopt;
    if (fn_eff_broker) {
        broker_opt = fn_eff_broker(btc_sec_id, std::nullopt);
    }

    const char* force_raw = std::getenv("BTC_SUB_FORCE_RAW_0x1843");
    bool use_raw = (force_raw && std::strcmp(force_raw, "1") == 0);

    // Route A (Default Safe Path): NNBiz_Qot_PushQot::SubOrUnSub -> merges into CQotSubBitMgr -> 0x1843
    if (!use_raw && pp_push_impl && *pp_push_impl && fn_sub_or_unsub) {
        NN_Prob2Item prob2;
        NN_KlineProb2SubItem item_1m;
        item_1m.exright_type = 0;   // EXRIGHT_TYPE_NONE
        item_1m.base_type = 2;      // BASE_KLINE_MINUTE
        item_1m.custom_number = 1;  // 1m
        item_1m.subscribe_type = 0; // SUBSCRIBE_TYPE_KLINE
        prob2.kline_items.insert(item_1m);

        constexpr unsigned long kProbeHandle = 0xA12B7C01UL;
        constexpr NN_QotSubBit  kBitCustomKline = QOT_SUB_BIT_CUSTOM_KLINE; // 0x2711
        bool sub_ok = fn_sub_or_unsub(
            *pp_push_impl, true, kProbeHandle, btc_sec_id,
            broker_opt, kBitCustomKline, 0u, prob2
        );
        char msg[320];
        std::snprintf(msg, sizeof(msg),
            "{\"ev\":\"route_a_sub_0x1843\",\"ok\":%s,\"sec_id\":%llu,\"mkt\":%u,\"has_broker\":%d,\"broker\":%u}",
            sub_ok ? "true" : "false",
            static_cast<unsigned long long>(btc_sec_id),
            static_cast<uint32_t>(mkt_type),
            broker_opt.has_value() ? 1 : 0,
            broker_opt.has_value() ? static_cast<uint32_t>(*broker_opt) : 0u);
        tap_log(msg);
    } else if (use_raw && fn_send_cmd && static_cast<uint32_t>(mkt_type) != 0) {
        // Route B (Direct Wire Fallback): IFTChannelProxy::SendCommand(CSChannelType=1, cmd_id=0x1843)
        // Warning: SubscribeSetReq replaces the market's active subscription set if sent raw!
        CSProtoData sub_data;
        sub_data.cmd_id = 0x1843; // 6211 = FTCmdStockQuoteSub.SubscribeSetReq
        sub_data.payload = encode_1m_subscribe_set_req(btc_sec_id, broker_opt);

        CSRequestExt ext;
        ext.timeout_ms = 10000;
        const char hdr[2] = {static_cast<char>(static_cast<uint32_t>(mkt_type) & 0xFFu), 0x00};
        ext.ext_head.assign(hdr, 2); // Verified @ DoSendSubReq 0x3f1eb7..0x3f202e

        unsigned long sub_seq = fn_send_cmd(
            CS_CHANNEL_QUOTE, sub_data, &ext,
            [](unsigned long req_id, CSProtoError err, const CSProtoData& rsp, const CSResponseExt*) {
                char line[256];
                std::snprintf(line, sizeof(line),
                    "{\"ev\":\"route_b_rsp_0x1843\",\"req_id\":%llu,\"err\":%u,\"cmd\":%u,\"bytes\":%zu}",
                    static_cast<unsigned long long>(req_id), static_cast<uint32_t>(err), rsp.cmd_id, rsp.payload.size());
                tap_log(line);
            },
            nullptr
        );
        char line[256];
        std::snprintf(line, sizeof(line),
            "{\"ev\":\"route_b_sent_0x1843\",\"seq\":%llu,\"sec_id\":%llu,\"mkt\":%u,\"bytes\":%zu}",
            static_cast<unsigned long long>(sub_seq),
            static_cast<unsigned long long>(btc_sec_id),
            static_cast<uint32_t>(mkt_type),
            sub_data.payload.size());
        tap_log(line);
    }

    // 1-shot 1m KlineReq pull (cmd_id = 0x1811 = 6161, last 3 bars) to immediately verify channel & scale
    if (fn_send_cmd) {
        CSProtoData req_data;
        req_data.cmd_id = 0x1811; // 6161 = FTCmdKline.KlineReq
        req_data.payload = encode_1m_kline_pull_req(btc_sec_id, 3, broker_opt);

        unsigned long seq_no = fn_send_cmd(
            CS_CHANNEL_QUOTE, req_data, nullptr,
            [btc_sec_id](unsigned long req_id, CSProtoError err, const CSProtoData& rsp, const CSResponseExt*) {
                char hdr[256];
                std::snprintf(hdr, sizeof(hdr),
                    "{\"ev\":\"pull_rsp_0x1811\",\"req_id\":%llu,\"err\":%u,\"cmd\":%u,\"bytes\":%zu}",
                    static_cast<unsigned long long>(req_id), static_cast<uint32_t>(err), rsp.cmd_id, rsp.payload.size());
                tap_log(hdr);
                if (static_cast<uint32_t>(err) == 0 && !rsp.payload.empty()) {
                    decode_and_log_stock_kline("pull_kline_0x1811", btc_sec_id, 10001, rsp.payload);
                }
            },
            nullptr
        );
        char msg[256];
        std::snprintf(msg, sizeof(msg),
            "{\"ev\":\"sent_pull_0x1811\",\"seq\":%llu,\"sec_id\":%llu,\"req_bytes\":%zu}",
            static_cast<unsigned long long>(seq_no),
            static_cast<unsigned long long>(btc_sec_id),
            req_data.payload.size());
        tap_log(msg);
    }
}

__attribute__((constructor))
void init_btc_1m_probe() {
    tap_log("{\"ev\":\"probe_loaded\",\"ver\":\"r1-65653\"}");
    if (const char* passive = std::getenv("BTC_SUB_PASSIVE_ONLY"); passive && std::strcmp(passive, "1") == 0) {
        return;
    }
    std::thread(worker_subscribe_btc_1m).detach();
}

} // namespace
