// HandLandmarker 实现 — 与官方 hand_landmarks_detector_graph.cc / hand_detector_graph.cc 对齐
// PC 参考: tools/ref_lm.py(顶部注释含全部字段来源与公式)
#include "infer/hand_landmarker.h"

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

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

namespace handwash {

namespace {

using hwtime::now_us;

constexpr int   kNumLM      = 21;
constexpr int   kDimPerLM   = 3;
constexpr float kTargetAngle = 1.5707963267948966f;   // 90°(官方 rotation_vector_target_angle)
constexpr float kScaleXY    = 2.6f;                   // RectTransformation scale_x/y
constexpr float kShiftY     = -0.5f;                  // RectTransformation shift_y
constexpr float kPi         = 3.14159265358979323846f;
// ROI RGB 缓冲边长(Init 预分配; 1280x720 整帧 RGB 要 2.76MB 连续 dma-heap, 与 ISP/NPU 抢不够)
constexpr uint32_t kRoiBufSide = 640;

inline float NormalizeRadians(float angle) {
    return angle - 2.f * kPi * std::floor((angle + kPi) / (2.f * kPi));
}

inline float Clampf(float x, float lo, float hi) { return x < lo ? lo : (x > hi ? hi : x); }

// 双线性采样单通道; src 指向 (x, y) 像素的通道 c
inline float Bilinear(const uint8_t* row0, const uint8_t* row1,
                      int x0, int x1, int c, float wx, float wy) {
    float v00 = row0[(size_t)x0 * 3 + c], v01 = row0[(size_t)x1 * 3 + c];
    float v10 = row1[(size_t)x0 * 3 + c], v11 = row1[(size_t)x1 * 3 + c];
    float top = v00 + (v01 - v00) * wx;
    float bot = v10 + (v11 - v10) * wx;
    return top + (bot - top) * wy;
}

}  // namespace

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

bool HandLandmarker::Init(const HandLandmarkerConfig& 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_landmarker: 输入不支持 (需要 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];

    // 输出识别(不依赖张量顺序): 63 = landmarks / world; 1 = presence / handedness
    bool got_lm = false, got_world = false, got_pres = false, got_hand = false;
    for (uint32_t i = 0; i < eng_.num_outputs(); ++i) {
        size_t n = eng_.output_elems(i);
        if (n == (size_t)kNumLM * kDimPerLM) {
            if (!got_lm) { lm_idx_ = (int)i; got_lm = true; }
            else         { world_idx_ = (int)i; got_world = true; }
        } else if (n == 1) {
            if (!got_pres) { pres_idx_ = (int)i; got_pres = true; }
            else           { hand_idx_ = (int)i; got_hand = true; }
        }
    }
    if (!got_lm || !got_world || !got_pres || !got_hand) {
        HW_ERR("hand_landmarker: 输出不匹配 (需要 MediaPipe 关键点模型: 63+1+1+63, 实际 %u 个输出)",
               eng_.num_outputs());
        return false;
    }

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

    lm_raw_.reserve(kNumLM * kDimPerLM);
    world_.reserve(kNumLM * kDimPerLM);
    pres_.reserve(1);
    hand_.reserve(1);

    inited_ = true;

    // ROI 小图缓冲: 在此预分配(此刻 VI/NPU 还没占 dma-heap, 必定成功), 避免运行期
    // 跟相机/显示抢连续内存; 手部 ROI 超过该边长时由 RGA 缩放塞进去(见 PrepareRoi)
    roi_buf_w_ = roi_buf_h_ = 0;
    if (dma_buf_alloc_auto((size_t)kRoiBufSide * kRoiBufSide * 3, &roi_rgb_)) {
        roi_buf_w_ = roi_buf_h_ = kRoiBufSide;
    } else {
        HW_WARN("hand_landmarker: ROI RGB 预分配失败 (%u KiB), 运行期再试",
                (unsigned)((size_t)kRoiBufSide * kRoiBufSide * 3 / 1024));
    }
    if (cfg_.verbose) {
        HW_LOG("hand_landmarker: 张量映射 lm=%d pres=%d hand=%d world=%d", lm_idx_, pres_idx_,
               hand_idx_, world_idx_);
        eng_.DumpInfo();
    }
    HW_LOG("hand_landmarker: 就绪 %dx%d presence_thresh=%.2f", in_w_, in_h_,
           cfg_.presence_thresh);
    return true;
}

// ---------------- 帧准备 ----------------

bool HandLandmarker::Prepare(const RgaImage& frame) {
    if (!inited_) return false;

    if (frame.format == RK_FORMAT_RGB_888) {   // 已是 RGB: 直接使用整帧
        rgb_ = frame;
        nv12_src_ = RgaImage{};
        frame_w_ = frame.width;
        frame_h_ = frame.height;
        return true;
    }

    // NV12(相机帧等): 只记录源帧, 转换留到 Process 里按手部 ROI 小图做
    // (整帧 1280x720 RGB 要 2.7MB 连续 dma-heap, 与 ISP/NPU 抢内存; ROI 通常 <1MB)
    nv12_src_ = frame;
    rgb_ = RgaImage{};
    frame_w_ = frame.width;
    frame_h_ = frame.height;
    return true;
}

// NV12 → 手部 ROI 小图 RGB(轴对齐外接矩形, 1:1 不缩放), 供 WarpRoi 采样
bool HandLandmarker::PrepareRoi(const Roi& roi, Roi* out) {
    if (!nv12_src_.valid()) return false;

    // 旋转后的正方形(边长 w,h)的外接矩形 + 2% 余量
    const float half = 0.5f * std::sqrt(roi.width * roi.width + roi.height * roi.height) * 1.02f;
    int x0 = (int)std::floor(roi.center_x - half);
    int y0 = (int)std::floor(roi.center_y - half);
    int x1 = (int)std::ceil(roi.center_x + half);
    int y1 = (int)std::ceil(roi.center_y + half);
    x0 &= ~1;   // NV12(YUV420) 裁剪矩形必须偶对齐, 否则 RGA 报 "yuv not align to 2"
    y0 &= ~1;
    x1 = (x1 + 1) & ~1;
    y1 = (y1 + 1) & ~1;
    x0 = std::max(0, std::min(x0, (int)frame_w_ - 2));
    y0 = std::max(0, std::min(y0, (int)frame_h_ - 2));
    x1 = std::max(x0 + 2, std::min(x1, (int)frame_w_));
    y1 = std::max(y0 + 2, std::min(y1, (int)frame_h_));
    uint32_t w = std::min<uint32_t>((uint32_t)(frame_w_ - x0) & ~3u,
                                    (uint32_t)(x1 - x0 + 3) & ~3u);
    uint32_t h = (uint32_t)(y1 - y0);
    if (w < 4 || h < 2) return false;

    if (!roi_rgb_.va) {   // 预分配失败时的兼底: 按需分配一次
        if (!dma_buf_alloc_auto((size_t)w * h * 3, &roi_rgb_)) {
            HW_ERR("hand_landmarker: ROI RGB 缓冲分配失败 (%ux%u)", w, h);
            return false;
        }
        roi_buf_w_ = w;
        roi_buf_h_ = h;
    }

    // ROI 超过缓冲边长时用 RGA 缩放进缓冲(手很大时损失一点解析度, 几何不变)
    float s = 1.f;
    if (w > roi_buf_w_ || h > roi_buf_h_) {
        s = std::min((float)roi_buf_w_ / (float)w, (float)roi_buf_h_ / (float)h);
    }
    uint32_t w_d = (uint32_t)((float)w * s);
    uint32_t h_d = (uint32_t)((float)h * s);
    w_d = std::max(4u, std::min(w_d, roi_buf_w_));
    h_d = std::max(2u, std::min(h_d, roi_buf_h_));

    // 行跨距用缓冲整行(与采样一致); 行字节 4 对齐由 640*3=1920 保证
    RgaImage dst = RgaImage::Rgb888(roi_rgb_.fd, roi_rgb_.va, w_d, h_d,
                                    roi_buf_w_ * 3);
    im_rect src_rect = { x0, y0, (int)w, (int)h };
    if (!RgaConvert(nv12_src_, dst, &src_rect, nullptr)) {
        HW_ERR("hand_landmarker: ROI NV12→RGB 转换失败 (%d,%d %ux%u → %ux%u)", x0, y0, w, h,
               w_d, h_d);
        return false;
    }
    rgb_ = dst;   // warp 采样坐标以 ROI 左上角为原点
    if (out) {
        out->center_x = (roi.center_x - (float)x0) * s;
        out->center_y = (roi.center_y - (float)y0) * s;
        out->width    = roi.width * s;
        out->height   = roi.height * s;
        out->rotation = roi.rotation;
    }
    return true;
}

// ---------------- ROI 几何 ----------------
// 官方公式(见头文件注释): 归一化版换算到像素版后:
//   rot = wrap(90° - atan2(-(kp2y-kp0y), kp2x-kp0x))
//   cx += 0.5*height*sin(rot); cy += -0.5*height*cos(rot)     (shift_y=-0.5)
//   side = max(width, height); w = h = side*2.6               (square_long + scale)
HandLandmarker::Roi HandLandmarker::ComputeRoi(const HandBox& box, uint32_t img_w, uint32_t img_h) {
    (void)img_w;
    (void)img_h;
    const float kp0x = box.kp[0][0], kp0y = box.kp[0][1];
    const float kp2x = box.kp[2][0], kp2y = box.kp[2][1];
    const float rot  = NormalizeRadians(kTargetAngle - std::atan2(-(kp2y - kp0y), kp2x - kp0x));

    float width  = box.x2 - box.x1;
    float height = box.y2 - box.y1;
    float cx     = (box.x1 + box.x2) * 0.5f;
    float cy     = (box.y1 + box.y2) * 0.5f;

    cx += 0.5f * height * std::sin(rot);
    cy += -0.5f * height * std::cos(rot);

    const float side = std::max(std::fabs(width), std::fabs(height));
    Roi roi;
    roi.center_x = cx;
    roi.center_y = cy;
    roi.width    = side * kScaleXY;
    roi.height   = side * kScaleXY;
    roi.rotation = rot;
    return roi;
}

// ---------------- ROI 裁剪(CPU 双线性, 任意角度) ----------------

void HandLandmarker::WarpRoi(const Roi& roi, uint8_t* dst, uint32_t dst_row_bytes) const {
    const float a = roi.width, b = roi.height;
    const float e = roi.center_x, f = roi.center_y;
    const float c = std::cos(roi.rotation), d = std::sin(roi.rotation);

    const uint8_t* src = (const uint8_t*)rgb_.va;
    const uint32_t sstride = rgb_.wstride * 3;
    const int sw = (int)rgb_.width, sh = (int)rgb_.height;
    const float max_x = (float)(sw - 2), max_y = (float)(sh - 2);

    for (int v = 0; v < in_h_; ++v) {
        const float yn2 = ((float)v + 0.5f) / (float)in_h_ - 0.5f;   // yn - 0.5
        const float ax  = a * c, ay = a * d;
        const float bx  = b * d, by = b * c;
        float px = ax * (0.5f / (float)in_w_ - 0.5f) - bx * yn2 + e;
        float py = ay * (0.5f / (float)in_w_ - 0.5f) + by * yn2 + f;
        const float step_x = ax / (float)in_w_;
        const float step_y = ay / (float)in_w_;
        uint8_t* drow = dst + (size_t)v * dst_row_bytes;

        for (int u = 0; u < in_w_; ++u, px += step_x, py += step_y) {
            float fx = Clampf(px, 0.f, max_x);
            float fy = Clampf(py, 0.f, max_y);
            int x0 = (int)fx, y0 = (int)fy;
            float wx = fx - (float)x0, wy = fy - (float)y0;
            const uint8_t* r0 = src + (size_t)y0 * sstride + (size_t)x0 * 3;
            const uint8_t* r1 = r0 + sstride;
            drow[u * 3 + 0] = (uint8_t)(Bilinear(r0, r1, 0, 1, 0, wx, wy) + 0.5f);
            drow[u * 3 + 1] = (uint8_t)(Bilinear(r0, r1, 0, 1, 1, wx, wy) + 0.5f);
            drow[u * 3 + 2] = (uint8_t)(Bilinear(r0, r1, 0, 1, 2, wx, wy) + 0.5f);
        }
    }
}

// ---------------- 推理 ----------------

bool HandLandmarker::ReadOutputs() {
    if (!eng_.ReadOutputFloat((uint32_t)lm_idx_, &lm_raw_)) return false;
    if (!eng_.ReadOutputFloat((uint32_t)pres_idx_, &pres_)) return false;
    if (!eng_.ReadOutputFloat((uint32_t)hand_idx_, &hand_)) return false;
    if (!eng_.ReadOutputFloat((uint32_t)world_idx_, &world_)) return false;
    return true;
}

bool HandLandmarker::Process(const HandBox& box, HandLandmarks* out) {
    if (!inited_ || !out) return false;
    const bool from_nv12 = nv12_src_.valid();
    if (!from_nv12 && !rgb_.valid()) return false;
    const uint64_t t0 = now_us();

    Roi roi = ComputeRoi(box, frame_w_, frame_h_);
    if (roi.width < 1.f || roi.height < 1.f) {
        if (cfg_.verbose) HW_WARN("hand_landmarker: 退化 ROI (w=%.1f h=%.1f), 跳过", roi.width,
                                  roi.height);
        return false;
    }

    // NV12 源: 先把本手的 ROI 转成小图(坐标平移到 ROI 原点)
    Roi warp_roi = roi;
    if (from_nv12 && !PrepareRoi(roi, &warp_roi)) return false;

    uint8_t* in = (uint8_t*)eng_.input_virt(0);
    if (!in) {
        HW_ERR("hand_landmarker: 输入缓冲不可用");
        return false;
    }
    const uint32_t in_row = eng_.input_row_bytes(0);

    uint64_t t1 = now_us();
    WarpRoi(warp_roi, in, in_row);
    uint64_t t2 = now_us();
    warp_ms_ = (double)(t2 - t1) / 1000.0;

    if (!eng_.Run()) return false;
    uint64_t t3 = now_us();
    infer_ms_ = (double)(t3 - t2) / 1000.0;

    if (!ReadOutputs()) return false;

    // 解码: xn=x/224, yn=y/224 → 反投影回原图(官方 LandmarkProjection 公式)
    const float c = std::cos(roi.rotation), d = std::sin(roi.rotation);
    out->presence   = pres_.empty() ? 0.f : pres_[0];
    out->handedness = hand_.empty() ? 0.f : hand_[0];
    for (int i = 0; i < kNumLM; ++i) {
        const float xn = lm_raw_[(size_t)i * 3 + 0] / (float)in_w_;
        const float yn = lm_raw_[(size_t)i * 3 + 1] / (float)in_h_;
        const float zz = lm_raw_[(size_t)i * 3 + 2] / (float)in_w_;
        out->pts[i][0] = roi.width * c * (xn - 0.5f) - roi.height * d * (yn - 0.5f) + roi.center_x;
        out->pts[i][1] = roi.width * d * (xn - 0.5f) + roi.height * c * (yn - 0.5f) + roi.center_y;
        out->pts[i][2] = zz;
    }

    last_ms_ = (double)(now_us() - t0) / 1000.0;
    return true;
}

bool HandLandmarker::ProcessPatch(const uint8_t* rgb224) {
    if (!inited_ || !rgb224) return false;
    const uint64_t t0 = now_us();
    if (!eng_.WriteInput(0, rgb224)) return false;
    uint64_t t1 = now_us();
    if (!eng_.Run()) return false;
    uint64_t t2 = now_us();
    if (!ReadOutputs()) return false;
    infer_ms_ = (double)(t2 - t1) / 1000.0;
    last_ms_ = (double)(now_us() - t0) / 1000.0;
    return true;
}

bool HandLandmarker::DumpPatch(const std::string& path) {
    if (!inited_) return false;
    const uint8_t* in = (const uint8_t*)eng_.input_virt(0);
    if (!in) return false;
    const uint32_t row = eng_.input_row_bytes(0);
    FILE* f = fopen(path.c_str(), "wb");
    if (!f) return false;
    for (int v = 0; v < in_h_; ++v) {
        fwrite(in + (size_t)v * row, 1, (size_t)in_w_ * 3, f);
    }
    fclose(f);
    return true;
}

}  // namespace handwash
