// test_display — P0: 两路相机实时上屏(不含推理), 验证显示链路与帧率
//
// 用法:
//   test_display [--conf conf/handwash.conf] [--fps 20] [--layout h|v|pip]
//                [--fit letterbox|crop] [--cams 名1,名2] [--run-seconds N]
//                [--mirror 0|1|all|无] [--snapshot 前缀]
//
// 数据流(每路一个采集线程):
//   相机 NV12(dma-buf fd) --RGA letterbox/crop--> 视频窗画布 XRGB8888(dma-buf) --LVGL--> /dev/fb0
//
// 线程模型:
//   采集线程(×2): GetFrame → 节流 → VideoPane::Push(RGA + 置脏) → PutFrame   [不碰 LVGL]
//   显示线程(主): TakeDirty → lv_obj_invalidate → Tick(lv_timer_handler)     [唯一 LVGL 调用者]
//
// 前置: scripts/board_init.sh(insmod mpp/rockit ko + 启动 rkaiq 3A 服务)
#include "camera/camera.h"
#include "camera/vi_camera.h"
#include "common/app_config.h"
#include "common/dma_buffer.h"
#include "common/log.h"
#include "common/time_utils.h"
#include "display/display_host.h"
#include "display/video_pane.h"

#include <atomic>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <string>
#include <thread>
#include <unistd.h>
#include <vector>

using namespace hwdisplay;

namespace {

std::atomic<bool> g_stop{false};
void OnSignal(int) { g_stop = true; }

// 一路相机 + 它的视频窗
struct CamCtx {
    std::string                   name;
    std::unique_ptr<FrameSource>  src;
    std::unique_ptr<VideoPane>    pane;
    std::thread                   thr;
    std::atomic<uint64_t>         frames_in{0};
    std::atomic<uint64_t>         dropped{0};
    std::atomic<uint64_t>         timeouts{0};
    bool                          mirror_conf = true;   // 来自 conf: display_mirror
    double                        fps       = 0;   // 上秒实际推送帧率
    uint64_t                      last_sec  = 0;
};

// 布局与 CPU 采样已抽到 display_host(与 handwash_app 共用)

}  // namespace

int main(int argc, char** argv) {
    std::string conf_path = "conf/handwash.conf";
    std::string layout    = "h";
    std::string cam_list;
    std::string mirror_opt;
    std::string snap_prefix;
    int         fps        = 20;
    int         run_sec    = 0;
    int         top_off    = 0;
    bool        crop       = false;

    for (int i = 1; i < argc; ++i) {
        std::string a = argv[i];
        if (a == "--conf" && i + 1 < argc)              conf_path = argv[++i];
        else if (a == "--fps" && i + 1 < argc)          fps = atoi(argv[++i]);
        else if (a == "--layout" && i + 1 < argc)       layout = argv[++i];
        else if (a == "--top" && i + 1 < argc)          top_off = atoi(argv[++i]);
        else if (a == "--cams" && i + 1 < argc)         cam_list = argv[++i];
        else if (a == "--run-seconds" && i + 1 < argc)  run_sec = atoi(argv[++i]);
        else if (a == "--mirror" && i + 1 < argc)       mirror_opt = argv[++i];
        else if (a == "--snapshot" && i + 1 < argc)     snap_prefix = argv[++i];
        else if (a == "--fit" && i + 1 < argc)          crop = (strcmp(argv[++i], "crop") == 0);
        else {
            HW_LOG("用法: %s [--conf P] [--fps N] [--layout h|v|pip] [--fit letterbox|crop]"
                   " [--cams n1,n2] [--mirror 0|1|all|none] [--snapshot 前缀] [--run-seconds N]",
                   argv[0]);
            return 1;
        }
    }

    signal(SIGINT, OnSignal);
    signal(SIGTERM, OnSignal);

    // ---- 配置: 取相机段(默认前两路) ----
    AppConfig cfg;
    if (!cfg.Load(conf_path)) return 1;

    std::vector<std::string> want;
    if (!cam_list.empty()) {
        size_t pos = 0;
        while (pos < cam_list.size()) {
            size_t c = cam_list.find(',', pos);
            want.push_back(cam_list.substr(pos, c == std::string::npos ? c : c - pos));
            if (c == std::string::npos) break;
            pos = c + 1;
        }
    } else {
        for (const auto& sec : cfg.Sections("camera.")) {
            want.push_back(sec.substr(strlen("camera.")));
            if (want.size() == 2) break;
        }
    }
    if (want.empty()) {
        HW_ERR("display: 配置 %s 里没有 [camera.*]", conf_path.c_str());
        return 2;
    }

    // ---- 打开相机 ----
    std::vector<std::unique_ptr<CamCtx>> cams;
    for (const auto& name : want) {
        std::string sec = "camera." + name;
        if (!cfg.Has(sec, "source") && !cfg.Has(sec, "device")) {
            HW_ERR("display: 配置里没有 [%s]", sec.c_str());
            return 2;
        }
        std::string source = cfg.GetStr(sec, "source", "rockit");

        CameraConfig cc;
        cc.pipe_id = cfg.GetInt(sec, "pipe", 0);
        cc.width   = (uint32_t)cfg.GetInt(sec, "width", 1280);
        cc.height  = (uint32_t)cfg.GetInt(sec, "height", 720);
        cc.device  = cfg.GetStr(sec, "device", "/dev/video22");
        cc.export_dmabuf = true;

        auto ctx = std::make_unique<CamCtx>();
        ctx->name = name;
        // 屏幕预览是否左右镜像(自拍视角; 只影响显示, 不影响推理)
        ctx->mirror_conf = cfg.GetBool(sec, "display_mirror", true);
        if (source == "v4l2") ctx->src.reset(new Camera());
        else                  ctx->src.reset(new ViCamera());
        if (!ctx->src->Open(cc) || !ctx->src->Start()) {
            HW_ERR("display: camera[%s](%s) 打开失败", name.c_str(), source.c_str());
            return 3;
        }
        HW_LOG("display: camera[%s] = %s %ux%u%s", name.c_str(), ctx->src->name(), cc.width,
               cc.height, source == "rockit" ? (" pipe=" + std::to_string(cc.pipe_id)).c_str() : "");
        cams.push_back(std::move(ctx));
    }

    // ---- 显示初始化(必须在主线程, 之后所有 LVGL 调用都在这里) ----
    if (!Init()) return 4;
    const int SW = Width(), SH = Height();

    int main_rc[4] = {0, 0, 0, 0}, sub_rc[4] = {0, 0, 0, 0};
    LayoutTwoPanes(layout, SW, SH, top_off, 30, main_rc, sub_rc);
    RgaFit fit = crop ? RgaFit::CropCenter : RgaFit::Letterbox;

    lv_obj_t* scr = lv_screen_active();
    for (size_t i = 0; i < cams.size() && i < 2; ++i) {
        const int* rc = (i == 0) ? main_rc : sub_rc;
        cams[i]->pane = std::make_unique<VideoPane>();
        if (!cams[i]->pane->Init(scr, cams[i]->name, rc[0], rc[1], rc[2], rc[3], fit)) return 4;
    }

    // 底部状态栏(一行 ASCII 文字: 各路帧率 + RGA 耗时 + 进程 CPU)
    lv_obj_t* bar = lv_obj_create(scr);
    lv_obj_remove_flag(bar, LV_OBJ_FLAG_SCROLLABLE);
    lv_obj_set_size(bar, SW, 30);
    lv_obj_set_pos(bar, 0, SH - 30);
    lv_obj_set_style_bg_color(bar, lv_color_hex(0x101010), 0);
    lv_obj_set_style_border_width(bar, 0, 0);
    lv_obj_set_style_radius(bar, 0, 0);
    lv_obj_t* lbl = lv_label_create(bar);
    lv_obj_set_style_text_color(lbl, lv_color_white(), 0);
    lv_obj_align(lbl, LV_ALIGN_LEFT_MID, 4, 0);
    lv_label_set_text(lbl, "display: starting...");   // 注: LVGL 默认字体无 CJK 字形, 用 ASCII

    // 镜像: 优先级 --mirror 显式 > conf 的 [camera.*] display_mirror(默认开)
    //   --mirror 0   只第一格镜像 | --mirror 1 只第二格 | --mirror all 都镜像 | none 都不镜像
    bool mir_override = !mirror_opt.empty();
    bool mir0 = false, mir1 = false;
    if (mirror_opt == "0")        mir0 = true;
    else if (mirror_opt == "1")   mir1 = true;
    else if (mirror_opt == "all") { mir0 = mir1 = true; }
    for (size_t i = 0; i < cams.size() && i < 2; ++i) {
        bool m = mir_override ? (i == 0 ? mir0 : mir1) : cams[i]->mirror_conf;
        cams[i]->pane->SetMirror(m);
    }

    HW_LOG("display: 布局=%s fit=%s 目标帧率=%d FPS mirror=%s%s, 开始出图", layout.c_str(),
           crop ? "crop" : "letterbox", fps, cams[0]->pane->mirror() ? "on" : "off",
           cams.size() > 1 ? (cams[1]->pane->mirror() ? "/on" : "/off") : "");

    // ---- 采集线程 ----
    // 节流: 用"累计目标时刻"而不是 last+interval —— 后者在 30fps 源 / 20fps 目标下会
    // 每帧都落在阈值前一点(33.3 < 41.6ms)而变成 15fps; 累计法能到 20fps(抖动 ±17ms)。
    const uint64_t interval_us = fps > 0 ? 1000000ULL / (uint64_t)fps : 0;
    for (auto& c : cams) {
        if (!c->pane) continue;
        CamCtx* ctx = c.get();
        ctx->thr = std::thread([ctx, interval_us, snap_prefix]() {
            uint64_t next_push = 0;
            bool     snapped   = false;
            while (!g_stop) {
                CameraFrame f;
                if (!ctx->src->GetFrame(&f, 1000)) {
                    if (!g_stop) ctx->timeouts++;
                    continue;
                }
                ctx->frames_in++;
                if (interval_us) {
                    uint64_t now = hwtime::now_us();
                    if (next_push == 0) next_push = now;
                    if (now < next_push) {
                        ctx->dropped++;
                        ctx->src->PutFrame(f);
                        continue;
                    }
                    next_push += interval_us;
                    if (now > next_push + interval_us)   // 落后太多(卡顿后): 重新对齐
                        next_push = now + interval_us;
                }
                ctx->pane->Push(f);          // RGA(内部记录耗时/置脏)
                ctx->src->PutFrame(f);

                // 首帧快照(拉回 PC 看画面/定位镜像问题用)
                if (!snapped && !snap_prefix.empty()) {
                    snapped = true;
                    const DmaBuffer& b = ctx->pane->buffer();
                    std::string fn = snap_prefix + "_" + ctx->name + ".rgb";
                    FILE* fp = fopen(fn.c_str(), "wb");
                    if (fp) {
                        fwrite(b.va, 1, b.size, fp);
                        fclose(fp);
                        HW_LOG("display: 快照已存 %s (%zu 字节 XRGB8888)", fn.c_str(), b.size);
                    }
                }
            }
        });
    }

    // ---- 主循环(显示线程) ----
    double   cpu_percent = 0;
    uint64_t win_start = hwtime::now_us();
    uint64_t next_stat = win_start + 1000000ULL;
    uint64_t t_begin   = win_start;

    while (!g_stop) {
        for (auto& c : cams)
            if (c->pane && c->pane->TakeDirty()) lv_obj_invalidate(c->pane->obj());

        uint32_t delay = Tick();
        uint64_t t1    = hwtime::now_us();

        if (t1 - win_start >= 500000ULL) {     // 每 0.5s 更新进程 CPU 展示
            cpu_percent = PollProcessCpu();
            win_start   = t1;
        }

        if (t1 >= next_stat) {                 // 每秒: 状态栏 + 日志
            char line[256];
            int  off   = 0;
            for (auto& c : cams) {
                if (!c->pane) continue;
                double dt = (double)(t1 - (c->last_sec ? c->last_sec : t1)) / 1e6;
                double f  = dt > 0 ? (double)c->pane->stats().pushed / dt : 0;
                c->last_sec = t1;
                off += snprintf(line + off, sizeof(line) - off, "%s%s %.0fFPS rga%.1fms  ",
                                c->name.c_str(), c->pane->mirror() ? "[mir]" : "", f,
                                c->pane->stats().rga_ms_avg);
                HW_LOG("display: [%s] in=%llu push=%llu drop=%llu timeout=%llu rga=%.2fms "
                       "err=%llu", c->name.c_str(),
                       (unsigned long long)c->frames_in.load(),
                       (unsigned long long)c->pane->stats().pushed,
                       (unsigned long long)c->dropped.load(),
                       (unsigned long long)c->timeouts.load(), c->pane->stats().rga_ms_avg,
                       (unsigned long long)c->pane->stats().errors);
            }
            snprintf(line + off, sizeof(line) - off, "| cpu %.0f%%", cpu_percent);
            lv_label_set_text(lbl, line);
            next_stat += 1000000ULL;
        }

        usleep(delay * 1000);
        if (run_sec > 0 && hwtime::now_us() - t_begin >= (uint64_t)run_sec * 1000000ULL) break;
    }

    // ---- 停止 ----
    g_stop = true;
    for (auto& c : cams)
        if (c->thr.joinable()) c->thr.join();
    for (auto& c : cams) {
        if (c->src) {
            c->src->Stop();
            c->src->Close();
        }
    }
    HW_LOG("display: 已退出");
    return 0;
}
