// HandDetector 实现 — 与官方 hand_detector_graph.cc 逐字段对齐
// 配置出处与 PC 参考验证: tools/ref_det.py(顶部注释含全部字段来源)
#include "infer/hand_detector.h"

#include "common/dma_buffer.h"
#include "common/log.h"
#include "common/time_utils.h"

#include <algorithm>
#include <cmath>
#include <cstring>

namespace handwash {

namespace {

using hwtime::now_us;

constexpr int   kNumBoxes    = 2016;
constexpr int   kNumCoords   = 18;
constexpr int   kNumKp       = 7;
constexpr float kCoordScale  = 192.0f;   // x/y/w/h_scale
constexpr float kScoreClip   = 100.0f;   // score_clipping_thresh
constexpr uint32_t kFillColor = 0x00000000u;   // BORDER_ZERO: 官方 letterbox 黑边填充

inline float Sigmoid(float x) {
    x = std::max(-kScoreClip, std::min(kScoreClip, x));
    return 1.0f / (1.0f + std::exp(-x));
}

// IoU(归一化框 {x1,y1,x2,y2}) — 对应官方 OverlapSimilarity(INTERSECTION_OVER_UNION)
inline float BoxIou(const float a[4], const float b[4]) {
    float x1 = std::max(a[0], b[0]), y1 = std::max(a[1], b[1]);
    float x2 = std::min(a[2], b[2]), y2 = std::min(a[3], b[3]);
    float inter = std::max(0.f, x2 - x1) * std::max(0.f, y2 - y1);
    float uni   = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter;
    return uni > 0.f ? inter / uni : 0.f;
}

}  // namespace

// ---------------- 工具 ----------------

void HandDetector::ComputeLetterbox(uint32_t w, uint32_t h, int dst, float* scale, int* pad_x,
                                    int* pad_y) {
    float s = std::min((float)dst / (float)w, (float)dst / (float)h);
    int nw  = (int)lroundf((float)w * s);
    int nh  = (int)lroundf((float)h * s);
    if (scale) *scale = s;
    if (pad_x) *pad_x = (dst - nw) / 2;
    if (pad_y) *pad_y = (dst - nh) / 2;
}

// ---------------- Init ----------------

bool HandDetector::Init(const HandDetectorConfig& cfg) {
    cfg_ = cfg;
    if (!eng_.Load(cfg_.model_path)) return false;

    const rknn_tensor_attr& ia = eng_.input_attr(0);
    if (ia.n_dims != 4 || ia.dims[0] != 1 || ia.dims[3] != 3) {
        HW_ERR("hand_detector: 输入不支持 (需要 NHWC [1,H,W,3], 实际 n_dims=%u)", ia.n_dims);
        return false;
    }
    in_h_ = (int)ia.dims[1];
    in_w_ = (int)ia.dims[2];

    // 输出识别(不依赖张量顺序): regressors = 2016×18, scores = 2016
    bool got_reg = false, got_cls = false;
    for (uint32_t i = 0; i < eng_.num_outputs(); ++i) {
        size_t n = eng_.output_elems(i);
        if (n == (size_t)kNumBoxes * kNumCoords) { reg_idx_ = (int)i; got_reg = true; }
        else if (n == kNumBoxes)                 { cls_idx_ = (int)i; got_cls = true; }
    }
    if (!got_reg || !got_cls) {
        HW_ERR("hand_detector: 输出不匹配 (需要 MediaPipe palm detection 模型: %d×%d + %d)",
               kNumBoxes, kNumCoords, kNumBoxes);
        return false;
    }

    if (!eng_.BindInput(0, RKNN_TENSOR_UINT8)) return false;   // 融合归一化(x/255 内嵌模型)
    if (!eng_.BindOutputsNative()) return false;               // 原生 INT8 + 手工反量化

    // letterbox 目标缓冲: 优先直接把 RGA 输出写进 rknn 输入 dma-buf(零拷贝)
    bool zero_copy_ok = false;
    if (cfg_.zero_copy) {
        int fd             = eng_.input_fd(0);
        uint32_t row_bytes = eng_.input_row_bytes(0);
        void* va           = eng_.input_virt(0);
        if (fd >= 0 && va && row_bytes % 3 == 0 && row_bytes / 3 >= (uint32_t)in_w_) {
            lb_img_  = RgaImage::Rgb888(fd, va, (uint32_t)in_w_, (uint32_t)in_h_, row_bytes);
            own_buf_ = false;
            zero_copy_ok = true;
        } else {
            HW_WARN("hand_detector: 零拷贝不可用(fd=%d row_bytes=%u), 回退拷贝路径", fd,
                    row_bytes);
        }
    }
    if (!zero_copy_ok) {
        if (!dma_buf_alloc_auto((size_t)in_w_ * in_h_ * 3, &lb_buf_)) {
            HW_ERR("hand_detector: 预处理缓冲分配失败");
            return false;
        }
        lb_img_  = RgaImage::Rgb888(lb_buf_.fd, lb_buf_.va, (uint32_t)in_w_, (uint32_t)in_h_);
        own_buf_ = true;
    }

    BuildAnchors();
    reg_.reserve((size_t)kNumBoxes * kNumCoords);
    cls_.reserve(kNumBoxes);
    cand_.reserve(64);

    inited_ = true;
    HW_LOG("hand_detector: 就绪 %dx%d thresh=%.2f nms=%.2f max_hands=%d 输入=%s", in_w_, in_h_,
           cfg_.score_thresh, cfg_.nms_iou, cfg_.max_hands,
           own_buf_ ? "拷贝" : "零拷贝(RGA→NPU dma-buf)");
    return true;
}

// 2016 个 anchor: 4 层 strides=8,16,16,16, 同 stride 层合并;
// 每层贡献 aspect_ratios(1 个) + 插值(1 个), 每格 anchor 中心相同;
// fixed_anchor_size=true ⇒ w=h=1(仅中心参与解码)
void HandDetector::BuildAnchors() {
    static const int kStrides[4] = {8, 16, 16, 16};
    cx_.clear();
    cy_.clear();
    cx_.reserve(kNumBoxes);
    cy_.reserve(kNumBoxes);
    for (int layer = 0; layer < 4;) {
        int end = layer;
        while (end < 4 && kStrides[end] == kStrides[layer]) ++end;
        const int n_per_cell = 2 * (end - layer);   // 每层 2 个(常规 + 插值)
        const int fm         = (in_w_ + kStrides[layer] - 1) / kStrides[layer];
        for (int y = 0; y < fm; ++y) {
            for (int x = 0; x < fm; ++x) {
                for (int k = 0; k < n_per_cell; ++k) {
                    cx_.push_back((x + 0.5f) / (float)fm);
                    cy_.push_back((y + 0.5f) / (float)fm);
                }
            }
        }
        layer = end;
    }
    if ((int)cx_.size() != kNumBoxes)
        HW_WARN("hand_detector: anchor 数量 %zu != %d (解码可能错位)", cx_.size(), kNumBoxes);
}

// ---------------- 推理入口 ----------------

bool HandDetector::Process(const RgaImage& frame_nv12, std::vector<HandBox>* out) {
    if (!inited_ || !out) return false;
    uint64_t t0 = now_us();

    float scale = 1.f;
    int px = 0, py = 0;
    if (!RgaLetterbox(frame_nv12, lb_img_, kFillColor, &scale, &px, &py)) return false;

    if (!RunAndEmit(scale, px, py, frame_nv12.width, frame_nv12.height, out)) return false;
    last_ms_ = (double)(now_us() - t0) / 1000.0;
    return true;
}

bool HandDetector::ProcessLetterboxed(const RgaImage& lb_rgb, float lb_scale, int lb_pad_x,
                                      int lb_pad_y, uint32_t src_w, uint32_t src_h,
                                      std::vector<HandBox>* out) {
    if (!inited_ || !out) return false;
    uint64_t t0 = now_us();
    if (!lb_rgb.va) {
        HW_ERR("hand_detector: ProcessLetterboxed 需要虚拟地址");
        return false;
    }
    if (!eng_.WriteInput(0, lb_rgb.va)) return false;
    if (!RunAndEmit(lb_scale, lb_pad_x, lb_pad_y, src_w, src_h, out)) return false;
    last_ms_ = (double)(now_us() - t0) / 1000.0;
    return true;
}

bool HandDetector::RunAndEmit(float lb_scale, int lb_pad_x, int lb_pad_y, uint32_t src_w,
                              uint32_t src_h, std::vector<HandBox>* out) {
    uint64_t t1 = now_us();
    if (!eng_.Run()) return false;
    uint64_t t2 = now_us();
    infer_ms_ = (double)(t2 - t1) / 1000.0;

    if (!eng_.ReadOutputFloat(reg_idx_, &reg_) || !eng_.ReadOutputFloat(cls_idx_, &cls_))
        return false;
    return RunPostprocess(reg_, cls_, lb_scale, lb_pad_x, lb_pad_y, src_w, src_h, out);
}

bool HandDetector::RunPostprocess(const std::vector<float>& reg, const std::vector<float>& cls,
                                  float lb_scale, int lb_pad_x, int lb_pad_y, uint32_t src_w,
                                  uint32_t src_h, std::vector<HandBox>* out) {
    if (!inited_ || !out) return false;
    DecodeRaw(reg, cls, &cand_);
    WeightedNms(&cand_, cfg_.nms_iou, cfg_.max_hands);
    if (cfg_.verbose) {
        for (size_t i = 0; i < cand_.size(); ++i) {
            const RawDet& d = cand_[i];
            HW_LOG("    [det%zu] score=%.3f cx=%.4f cy=%.4f w=%.4f h=%.4f", i, d.score, d.cx,
                   d.cy, d.w, d.h);
        }
    }
    EmitBoxes(cand_, lb_scale, lb_pad_x, lb_pad_y, src_w, src_h, out);
    return true;
}

// ---------------- 后处理 ----------------

// 解码(官方 TensorsToDetections): reverse_output_order=true ⇒ 原始顺序 (x,y,w,h);
// score=sigmoid(clip(raw,±100)); 中心/宽高按 192 归一(anchor w=h=1);
// 过滤: score<thresh / w,h<0 / NaN
void HandDetector::DecodeRaw(const std::vector<float>& reg, const std::vector<float>& cls,
                             std::vector<RawDet>* out) const {
    out->clear();
    const int n = std::min((int)(reg.size() / kNumCoords), (int)cls.size());
    for (int i = 0; i < n; ++i) {
        const float s = Sigmoid(cls[i]);
        if (s < cfg_.score_thresh) continue;

        const float* r = &reg[(size_t)i * kNumCoords];
        const float w  = r[2] / kCoordScale;
        const float h  = r[3] / kCoordScale;
        if (w < 0.f || h < 0.f || !std::isfinite(w) || !std::isfinite(h)) continue;

        RawDet d;
        d.score = s;
        d.cx    = r[0] / kCoordScale + cx_[i];
        d.cy    = r[1] / kCoordScale + cy_[i];
        d.w     = w;
        d.h     = h;
        for (int k = 0; k < kNumKp; ++k) {
            d.kp[k][0] = r[4 + 2 * k] / kCoordScale + cx_[i];
            d.kp[k][1] = r[4 + 2 * k + 1] / kCoordScale + cy_[i];
        }
        if (cfg_.verbose)
            HW_LOG("    [cand i=%d] score=%.4f anchor=(%.4f,%.4f) r=(%.2f,%.2f,%.2f,%.2f) "
                   "cx=%.4f cy=%.4f w=%.4f h=%.4f",
                   i, s, cx_[i], cy_[i], r[0], r[1], r[2], r[3], d.cx, d.cy, d.w, d.h);
        out->push_back(d);
    }
}

// 加权 NMS(官方 WEIGHTED 算法): 按分数降序取第一个 → 与其 IoU>thresh 的成组,
// 组内位置/关键点按分数加权平均后输出(分数保持组内最高); 循环至无剩余或达上限
void HandDetector::WeightedNms(std::vector<RawDet>* dets, float iou_thresh, int max_out) {
    if (dets->empty()) return;

    std::vector<RawDet> in = std::move(*dets);
    std::stable_sort(in.begin(), in.end(),
                     [](const RawDet& a, const RawDet& b) { return a.score > b.score; });

    std::vector<size_t> remained(in.size()), cand, rest;
    for (size_t i = 0; i < in.size(); ++i) remained[i] = i;

    std::vector<RawDet> out;
    out.reserve(max_out > 0 ? (size_t)max_out : in.size());

    while (!remained.empty() && (max_out <= 0 || (int)out.size() < max_out)) {
        const size_t n_before = remained.size();
        const RawDet& top     = in[remained[0]];

        cand.clear();
        rest.clear();
        float top_box[4] = {top.cx - top.w / 2, top.cy - top.h / 2, top.cx + top.w / 2,
                            top.cy + top.h / 2};
        for (size_t idx : remained) {
            const RawDet& d = in[idx];
            float b[4]      = {d.cx - d.w / 2, d.cy - d.h / 2, d.cx + d.w / 2, d.cy + d.h / 2};
            if (BoxIou(b, top_box) > iou_thresh) cand.push_back(idx);
            else rest.push_back(idx);
        }

        RawDet merged = top;
        if (!cand.empty()) {   // 组内按分数加权平均(cand 含 top 自身)
            float total = 0.f;
            for (size_t idx : cand) total += in[idx].score;
            if (total > 0.f) {
                float sc = 0.f, sx = 0.f, sy = 0.f, sw = 0.f, sh = 0.f;
                float skp[kNumKp][2] = {};
                for (size_t idx : cand) {
                    const RawDet& d = in[idx];
                    const float s   = d.score;
                    sc += s;
                    sx += d.cx * s;
                    sy += d.cy * s;
                    sw += d.w * s;
                    sh += d.h * s;
                    for (int k = 0; k < kNumKp; ++k) {
                        skp[k][0] += d.kp[k][0] * s;
                        skp[k][1] += d.kp[k][1] * s;
                    }
                }
                (void)sc;
                merged.cx = sx / total;
                merged.cy = sy / total;
                merged.w  = sw / total;
                merged.h  = sh / total;
                for (int k = 0; k < kNumKp; ++k) {
                    merged.kp[k][0] = skp[k][0] / total;
                    merged.kp[k][1] = skp[k][1] / total;
                }
            }
        }
        out.push_back(merged);

        if (rest.size() == n_before) break;   // 无任何移除(退化情形, 防死循环)
        remained.swap(rest);
    }

    *dets = std::move(out);
}

// 归一化坐标 → 原图像素: orig = (norm * 192 - pad) / scale
void HandDetector::EmitBoxes(const std::vector<RawDet>& raw, float lb_scale, int lb_pad_x,
                             int lb_pad_y, uint32_t src_w, uint32_t src_h,
                             std::vector<HandBox>* out) const {
    out->clear();
    const float sx = (lb_scale > 0.f) ? 1.f / lb_scale : 0.f;
    auto mx        = [&](float nx) { return (nx * (float)in_w_ - (float)lb_pad_x) * sx; };
    auto my        = [&](float ny) { return (ny * (float)in_h_ - (float)lb_pad_y) * sx; };
    (void)src_w;
    (void)src_h;

    for (const RawDet& d : raw) {
        HandBox b;
        b.score = d.score;
        b.x1    = mx(d.cx - d.w / 2);
        b.y1    = my(d.cy - d.h / 2);
        b.x2    = mx(d.cx + d.w / 2);
        b.y2    = my(d.cy + d.h / 2);
        for (int k = 0; k < kNumKp; ++k) {
            b.kp[k][0] = mx(d.kp[k][0]);
            b.kp[k][1] = my(d.kp[k][1]);
        }
        out->push_back(b);
    }
}

}  // namespace handwash
