// test_vi — rockit VI 采集单测(可独立运行)
//
// 用法:
//   test_vi [--loops 60] [--w 1280] [--h 720] [--out-prefix /root/handwash/vi_out]
//
// 功能:
//   1) rockit VI 初始化 + 连续采集, 统计 FPS(帧间隔);
//   2) 验证 MB_BLK 零拷贝: Handle2Fd 导出 dma-buf fd;
//   3) RGA letterbox: VI 帧(fd) -> RGB 192x192 / 224x224(fd), 存文件;
//   4) 与 V4L2 路径(test_rga --camera)输出可直接对比。
//
// 前置: scripts/board_init.sh(insmod ko + 3A 服务)
#include "camera/vi_camera.h"
#include "common/dma_buffer.h"
#include "common/log.h"
#include "common/time_utils.h"
#include "rga/rga_utils.h"

#include <cstdio>
#include <cstring>
#include <fstream>
#include <string>

namespace {
using hwtime::now_ms;   // 统一时间源(common/time_utils.h)
bool write_file(const std::string& fn, const void* data, size_t size) {
    std::ofstream of(fn, std::ios::binary);
    if (!of) return false;
    of.write(static_cast<const char*>(data), (std::streamsize)size);
    return (bool)of;
}
}  // namespace

int main(int argc, char** argv) {
    int loops              = 60;
    int pipe_id            = 0;
    uint32_t w = 1280, h = 720;
    std::string out_prefix = "/root/handwash/vi_out";

    for (int i = 1; i < argc; ++i) {
        std::string a = argv[i];
        if (a == "--loops" && i + 1 < argc) loops = atoi(argv[++i]);
        else if (a == "--pipe" && i + 1 < argc) pipe_id = atoi(argv[++i]);
        else if (a == "--w" && i + 1 < argc) w = (uint32_t)atoi(argv[++i]);
        else if (a == "--h" && i + 1 < argc) h = (uint32_t)atoi(argv[++i]);
        else if (a == "--out-prefix" && i + 1 < argc) out_prefix = argv[++i];
        else {
            HW_LOG("用法: %s [--loops N] [--pipe 0|1] [--w W] [--h H] [--out-prefix P]", argv[0]);
            return 1;
        }
    }

    ViCamera cam;
    CameraConfig cfg;
    cfg.pipe_id   = pipe_id;
    cfg.width     = w;
    cfg.height    = h;
    cfg.buf_count = 6;
    if (!cam.Open(cfg)) return 1;
    if (!cam.Start()) return 1;

    // ---- 首帧: 验证 fd + RGA 链路 ----
    CameraFrame f;
    if (!cam.GetFrame(&f, 3000)) {
        HW_ERR("取帧失败 (scripts/board_init.sh 跑了吗?)");
        return 2;
    }
    HW_LOG("VI 帧: %ux%u stride=%u size=%zu vaddr=%p dmabuf_fd=%d", f.width, f.height,
           f.wstride, f.size, f.vaddr, f.dmabuf_fd);

    DmaBuffer out192, out224;
    if (!dma_buf_alloc_auto(192 * 192 * 3, &out192)) return 3;
    if (!dma_buf_alloc_auto(224 * 224 * 3, &out224)) return 3;

    RgaImage src    = RgaImage::Nv12(f.dmabuf_fd, f.vaddr, f.width, f.height, f.wstride);
    RgaImage dst192 = RgaImage::Rgb888(out192.fd, out192.va, 192, 192);
    RgaImage dst224 = RgaImage::Rgb888(out224.fd, out224.va, 224, 224);
    if (!RgaLetterbox(src, dst192, 0x72727272)) return 3;
    if (!RgaLetterbox(src, dst224, 0x72727272)) return 3;
    dma_buf_sync_start(out192.fd);
    dma_buf_sync_start(out224.fd);
    write_file(out_prefix + "_det192.rgb", out192.va, 192 * 192 * 3);
    write_file(out_prefix + "_lm224.rgb", out224.va, 224 * 224 * 3);
    HW_LOG("已保存 %s_det192.rgb / %s_lm224.rgb", out_prefix.c_str(), out_prefix.c_str());

    // RGA 时延
    double t0 = now_ms();
    for (int i = 0; i < 20; ++i)
        if (!RgaLetterbox(src, dst192, 0x72727272)) return 3;
    HW_LOG("VI->RGA letterbox 192x192: %.2f ms/call", (now_ms() - t0) / 20);

    cam.PutFrame(f);

    // ---- 连续采集统计 ----
    double t_begin = now_ms();
    uint64_t last_ts = 0;
    double sum_interval = 0;
    int got = 0, timeout = 0;
    for (int i = 0; i < loops; ++i) {
        CameraFrame ff;
        if (!cam.GetFrame(&ff, 2000)) {
            timeout++;
            continue;
        }
        got++;
        if (last_ts) sum_interval += (double)(ff.timestamp_us - last_ts) / 1000.0;
        last_ts = ff.timestamp_us;
        cam.PutFrame(ff);
    }
    double elapsed = now_ms() - t_begin;

    HW_LOG("==== VI RESULT ====");
    HW_LOG("frames=%d timeout=%d wall=%.1f ms", got, timeout, elapsed);
    if (got > 0) {
        HW_LOG("fps=%.2f, avg_interval=%.2f ms", got * 1000.0 / elapsed,
               sum_interval / (got - 1 > 0 ? got - 1 : 1));
    }
    cam.Stop();
    cam.Close();
    return got > 0 ? 0 : 2;
}
