// handwash_app — 应用组装层(只做组装, 不含算法)
//
// 职责:
//   1) 读配置 → 路↔管线绑定、频率、模型路径、业务规则、屏幕显示参数
//   2) 为每个 [camera.*] 创建帧源(Camera / ViCamera)并启动
//   3) 为每个 [camera.*] 起一个 FrameHub(唯一采集线程 + 多订阅者)
//   4) 为每个 [pipeline.*] 创建 StreamPipeline(向 hub 订阅 + 注入推理链)
//   5) [display] 开启时: LVGL 首页或两格实时视频调试窗
//   6) 组装业务: FusionEngine + EventSink
//   7) 生命周期: 启动 / 主循环(显示 tick + 健康统计) / SIGINT 退出 / 逆序停止
//
// 用法: handwash_app [--conf conf/handwash.conf] [--run-seconds N]
#include "business/event_sink.h"
#include "business/fusion_engine.h"
#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/board_video_player.h"
#include "display/overlay.h"
#include "display/overlay_model.h"
#include "display/ui/flow/flow_controller.h"
#include "display/ui/home/home_controller.h"
#include "display/video_pane.h"
#include "infer/face_tracker.h"
#include "infer/face_gallery.h"
#include "infer/hand_detector.h"
#include "infer/hand_landmarker.h"
#include "infer/stable_slots.h"
#include "infer/stgcn.h"
#include "pipeline/frame_hub.h"
#include "pipeline/frame_source.h"
#include "pipeline/stream_pipeline.h"
#include "rga/rga_utils.h"

#include <algorithm>
#include <atomic>
#include <csignal>
#include <cstdio>
#include <cstring>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <unistd.h>
#include <vector>

using namespace handwash;

namespace {

volatile sig_atomic_t g_stop = 0;
void OnSignal(int) { g_stop = 1; }

// 引导页右下轻提示的可读名字(日志/诊断用)
const char* FeedbackName(hwdisplay::ui::HandFeedback f) {
    using hwdisplay::ui::HandFeedback;
    switch (f) {
        case HandFeedback::Observing: return "还没看出动作";
        case HandFeedback::Matched:   return "看到：当前动作(对啦)";
        case HandFeedback::Other:     return "看到：其它动作";
        case HandFeedback::Missing:   return "双手未入镜";
        case HandFeedback::Unclear:   return "动作看不清";
        case HandFeedback::Offline:   return "相机异常";
    }
    return "?";
}

// 取景缓冲(首页人脸 / 引导页手部)。管线线程用 RGA 写 dma-buf, 显示线程加锁复制到 LVGL 画布。
// 每个取景各自订阅一路相机(fps 由 hub 订阅控制), 不与推理管线抢投递。
struct PreviewBuffer {
    DmaBuffer pixels;
    DmaBuffer mirror_tmp;
    std::mutex pixels_mutex;
    bool     mirror = false;
    int      width  = 0;
    int      height = 0;
    uint32_t fill   = 0xFF695B31u;   // letterbox 填充(按 BGRA 字节序, 取卡片底色)
    std::atomic<bool> active{true};
    std::atomic<bool> dirty{false};
    std::atomic<uint64_t> last_success_us{0};
    std::atomic<uint64_t> pushed{0};
    std::atomic<uint64_t> shown{0};
    std::atomic<uint64_t> errors{0};

    ~PreviewBuffer() { dma_buf_free(&mirror_tmp); dma_buf_free(&pixels); }

    bool Init(int w, int h, bool use_mirror, uint32_t fill_color) {
        width  = w;
        height = h;
        fill   = fill_color;
        const size_t bytes = (size_t)w * h * 4;
        if (!dma_buf_alloc_auto(bytes, &pixels)) return false;
        mirror = use_mirror && dma_buf_alloc_auto(bytes, &mirror_tmp);
        if (use_mirror && !mirror) HW_WARN("app: 取景镜像缓冲不可用，显示原始方向");
        std::memset(pixels.va, 0, bytes);
        return true;
    }

    void Push(const CameraFrame& frame) {
        if (!active.load(std::memory_order_acquire)) return;
        std::lock_guard<std::mutex> lock(pixels_mutex);
        const RgaImage src = RgaImage::Nv12(frame.dmabuf_fd, frame.vaddr,
                                            frame.width, frame.height, frame.wstride);
        const RgaImage dst = RgaImage::Xrgb8888(pixels.fd, pixels.va, width, height);
        bool ok = false;
        if (mirror) {
            const RgaImage mid = RgaImage::Xrgb8888(mirror_tmp.fd, mirror_tmp.va, width, height);
            // imfill 的颜色按低字节 R、G、B、A 写入此 BGRA 目标格式。
            ok = RgaFitBlit(src, mid, RgaFit::Letterbox, fill) && RgaFlipH(mid, dst);
        } else {
            ok = RgaFitBlit(src, dst, RgaFit::Letterbox, fill);
        }
        if (ok) {
            pushed.fetch_add(1, std::memory_order_relaxed);
            last_success_us.store(hwtime::now_us(), std::memory_order_release);
            dirty.store(true, std::memory_order_release);
        } else {
            errors.fetch_add(1, std::memory_order_relaxed);
        }
    }

    bool TakeDirty() { return dirty.exchange(false, std::memory_order_acq_rel); }
};

// 每管线的推理上下文(type 决定装什么)
struct PipeCtx {
    DmaBuffer pre_buf;                       // 占位预处理缓冲(人脸链路预留)
    RgaImage  pre_img;
    std::unique_ptr<HandDetector>    detector;    // type=hand: 手掌检测器
    std::unique_ptr<HandLandmarker>  landmarker;  // type=hand: 21 点关键点
    std::unique_ptr<Stgcn>           stgcn;       // type=hand: 动作识别
    std::unique_ptr<StableHandSlots> slots;       // type=hand: 稳定左右槽位(42 点)
    std::unique_ptr<FaceTracker>     face_tracker;  // type=face: 人脸检测/追踪(InspireFace)
    DmaBuffer        infer_copy;               // type=face: 识别帧私有副本(先复制再归还 VI 缓冲)
    bool             infer_copy_warned = false;      // 副本分配失败只警告一次
    uint64_t         infer_copy_errors = 0;
    uint64_t face_infer_interval_us = 200000;
    uint64_t next_face_infer_us = 0;
    std::atomic<uint64_t> face_inferred{0};
    std::atomic<int>* hand_phase = nullptr;          // 0=首页/非教学，正数=本轮七步教学
    int last_hand_phase = -1;                        // 仅本管线线程访问
    FaceGallery*    face_gallery = nullptr;         // SDK 持久化特征库(进程内共享)
    int             known_person_id = -1;
    std::string     known_person_name;
    int             face_candidate = -1;             // 仅面部管线线程访问
    int             face_candidate_frames = 0;
    int             face_logged_id = -1;
    std::atomic<int> last_recognized_id{-1};
    std::string      cam_name;            // 本管线绑定的相机名(发布叠加数据用)
    std::string      kind;                // hand | face, 给首页控制器汇总观测用
    FusionEngine*   fusion  = nullptr;    // 业务回调
    OverlayChannel* overlay = nullptr;    // 叠加数据发布(显示端消费)
    StatusChannel*  status  = nullptr;    // 状态数据发布
    float           presence_thresh = 0.5f;
    float           cand_pts[2][21][3];   // 本帧候选手(仅本管线线程访问)
    float           cand_world[2][63];
    std::atomic<int> last_det_count{0};
    std::atomic<uint64_t> last_det_ts_us{0};
    std::atomic<int> windows{0};
    std::atomic<int>   last_step{0};        // 最近一个 STGCN 窗口的类别(1..7, 0=无)
    std::atomic<float> last_step_conf{0.f};
    std::atomic<uint64_t> last_step_ts_us{0};
};

// 业务事件 → 日志 + 屏幕状态区
class DisplayEventSink : public EventSink {
public:
    explicit DisplayEventSink(StatusChannel* ch) : ch_(ch) {}

    void Emit(const WashEvent& ev) override {
        log_.Emit(ev);   // 保留原有日志输出
        if (!ch_) return;
        StatusData st   = ch_->Snapshot();
        st.last_steps   = (int)ev.steps.size();
        st.last_ts_us   = ev.end_us;
        st.last_aligned = ev.identity_aligned;
        st.last_name    = ev.name;
        ch_->Publish(st);
    }

private:
    StatusChannel* ch_ = nullptr;
    LogEventSink   log_;
};

}  // namespace

int main(int argc, char** argv) {
    std::string conf_path = "conf/handwash.conf";
    int run_seconds       = 0;   // 0 = 无限(靠信号退出)

    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 == "--run-seconds" && i + 1 < argc) run_seconds = atoi(argv[++i]);
        else {
            HW_LOG("用法: %s [--conf conf/handwash.conf] [--run-seconds N]", argv[0]);
            return 1;
        }
    }

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

    // ---- 配置 ----
    AppConfig cfg;
    if (!cfg.Load(conf_path)) return 1;
    hwlog::level() = cfg.GetInt("system", "log_level", 2);

    // ---- 1) 相机池: 遍历 [camera.*] ----
    // ⚠️ 这里只创建对象(**不 Open**): VI 一开流就会从 dma-heap 拿十几 MB 连续内存,
    //    先加载 NPU 模型(需要连续 4MB+)才能避免 dma-heap 碎片导致的 rknn_init 失败。
    //    真正的 Open/开始流放在第 4) 步, 在模型与显示缓冲都分配完之后。
    std::map<std::string, std::unique_ptr<FrameSource>> cams;
    std::map<std::string, CameraConfig>                 cam_cfgs;
    std::map<std::string, bool>                         cam_is_rockit;
    for (const auto& sec : cfg.Sections("camera.")) {
        std::string name   = sec.substr(strlen("camera."));
        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");
        // VI 缓冲数直接吃 dma-heap(48MB 与 NPU 模型/ISP 共享): 1280x720 NV12 每缓1.38MB,
        // 两路各 6 ↔ 各 4 可省 ~5.5MB(实测关键点全帧 RGB 缓冲需要这块空间)
        cc.buf_count     = cfg.GetInt(sec, "buf_count", 4);
        cc.export_dmabuf = true;

        std::unique_ptr<FrameSource> fs;
        if (source == "v4l2") fs.reset(new Camera());
        else                  fs.reset(new ViCamera());
        cam_cfgs[name]     = cc;
        cam_is_rockit[name] = (source != "v4l2");
        cams[name]         = std::move(fs);
    }
    if (cams.empty()) {
        HW_ERR("app: 配置里没有任何 [camera.*]");
        return 2;
    }

    // ---- 1b) 帧分发中枢: 每路相机一个 FrameHub(唯一采集线程, 可多订阅) ----
    std::map<std::string, std::unique_ptr<FrameHub>> hubs;
    for (auto& kv : cams)
        hubs[kv.first] = std::make_unique<FrameHub>(kv.first, kv.second.get());

    // ---- 2) 业务层: FusionEngine + EventSink ----
    // 显示数据通道(推理/业务线程 → 显示线程; 单槽 latest-wins)
    StatusChannel  status_ch;
    // 每路相机一个叠加通道(手部管线写 hands, 人脸管线写 faces)
    std::map<std::string, std::unique_ptr<OverlayChannel>> overlay_chs;
    for (auto& kv : cams) overlay_chs[kv.first] = std::make_unique<OverlayChannel>();

    FusionEngine::Config fcfg;
    fcfg.session_gap_ms     = (uint64_t)cfg.GetInt("business", "session_gap_ms", 3000);
    fcfg.identity_window_ms = (uint64_t)cfg.GetInt("business", "identity_window_ms", 5000);
    fcfg.require_identity   = cfg.GetBool("business", "require_identity", false);
    DisplayEventSink sink(&status_ch);
    FusionEngine fusion(fcfg, &sink);
    HW_LOG("app: 业务就绪(session_gap=%llums, identity_window=%llums)",
           (unsigned long long)fcfg.session_gap_ms,
           (unsigned long long)fcfg.identity_window_ms);

    // 只有七步教学页启用手部关键点与动作识别；首页仍保留手掌检测作为启动信号。
    std::atomic<int> hand_phase{0};

    // ---- 3) 管线池: 遍历 [pipeline.*] ----
    std::vector<std::unique_ptr<StreamPipeline>> pipes;
    std::vector<std::unique_ptr<PipeCtx>>        ctxs;
    std::unique_ptr<FaceGallery> face_gallery;

    for (const auto& sec : cfg.Sections("pipeline.")) {
        std::string pname    = sec.substr(strlen("pipeline."));
        std::string type     = cfg.GetStr(sec, "type", "passthrough");   // hand | face | ...
        std::string cam_name = cfg.GetStr(sec, "camera");
        auto it              = cams.find(cam_name);
        if (it == cams.end()) {
            HW_ERR("app: pipeline[%s] 引用了不存在的 camera=%s", pname.c_str(),
                   cam_name.c_str());
            return 2;
        }

        // 处理帧率: pipeline 段优先, 缺省回退到 camera 段
        int process_fps = cfg.Has(sec, "process_fps")
                              ? cfg.GetInt(sec, "process_fps", 10)
                              : cfg.GetInt("camera." + cam_name, "process_fps", 10);

        StreamPipeline::Config pc;
        pc.process_fps = process_fps;
        auto pipe = std::make_unique<StreamPipeline>(pname, hubs[cam_name].get(), pc);
        auto ctx  = std::make_unique<PipeCtx>();
        ctx->cam_name = cam_name;

        if (type == "hand") {
            ctx->hand_phase = &hand_phase;
            HandDetectorConfig dcfg;
            dcfg.model_path   = cfg.GetStr(sec, "detector", "models/hand_detector_rv1106.rknn");
            dcfg.score_thresh = cfg.GetFloat(sec, "det_conf", 0.5f);
            dcfg.max_hands    = cfg.GetInt(sec, "max_hands", 2);
            dcfg.zero_copy    = cfg.GetBool(sec, "zero_copy", true);
            ctx->detector.reset(new HandDetector());
            if (!ctx->detector->Init(dcfg)) {
                HW_ERR("app: pipeline[%s] 手掌检测器初始化失败 (%s)", pname.c_str(),
                       dcfg.model_path.c_str());
                return 3;
            }

            // 关键点 → 稳定槽位 → STGCN(动作识别) → fusion.OnAction
            HandLandmarkerConfig lcfg;
            lcfg.model_path      = cfg.GetStr(sec, "landmarks",
                                              "models/hand_landmarks_detector_rv1106.rknn");
            lcfg.presence_thresh = 0.5f;
            ctx->presence_thresh = lcfg.presence_thresh;
            ctx->landmarker.reset(new HandLandmarker());
            if (!ctx->landmarker->Init(lcfg)) {
                HW_ERR("app: pipeline[%s] 关键点模型初始化失败 (%s)", pname.c_str(),
                       lcfg.model_path.c_str());
                return 3;
            }

            StgcnConfig scfg;
            scfg.model_path = cfg.GetStr(sec, "stgcn", "models/handwash_stgcn_2d_rv1106.rknn");
            scfg.frames     = cfg.GetInt(sec, "stgcn_window", 32);
            scfg.stride     = cfg.GetInt(sec, "stgcn_stride", 8);
            // 特征模式: stgcn_feature=image2d|world3d|scene3d(旧键 stgcn_world3d 仍兼容)
            const std::string feat = cfg.GetStr(sec, "stgcn_feature", "");
            if (feat == "scene3d")       scfg.feature = StgcnFeature::Scene3d;
            else if (feat == "world3d")  scfg.feature = StgcnFeature::World3d;
            else if (feat == "image2d")  scfg.feature = StgcnFeature::Image2d;
            else scfg.feature = cfg.GetBool(sec, "stgcn_world3d", false)
                                    ? StgcnFeature::World3d : StgcnFeature::Image2d;
            ctx->stgcn.reset(new Stgcn());
            if (!ctx->stgcn->Init(scfg)) {
                HW_ERR("app: pipeline[%s] STGCN 初始化失败 (%s)", pname.c_str(),
                       scfg.model_path.c_str());
                return 3;
            }
            ctx->slots.reset(new StableHandSlots());
            ctx->fusion  = &fusion;
            ctx->overlay = overlay_chs[cam_name].get();
            ctx->status  = &status_ch;

            HW_LOG("app: pipeline[%s] 手部链就绪 (det=%s, lm=%s, stgcn=%s, win=%d/%d)",
                   pname.c_str(), dcfg.model_path.c_str(), lcfg.model_path.c_str(),
                   scfg.model_path.c_str(), scfg.frames, scfg.stride);
        } else if (type == "face" && cfg.GetStr(sec, "sdk", "inspireface") == "inspireface") {
            // 人脸检测/追踪(InspireFace LIGHT_TRACK): 帧率低(5FPS)即可
            const int infer_fps = std::clamp(cfg.GetInt(sec, "infer_fps", 5), 1, 30);
            ctx->face_infer_interval_us = 1000000ULL / infer_fps;
            FaceTrackerConfig ftc;
            ftc.pack_path  = cfg.GetStr(sec, "pack", "models/Gundam_RV1106.tar");
            ftc.detect_level = cfg.GetInt(sec, "detect_level", 320);
            ftc.max_faces    = cfg.GetInt(sec, "max_faces", 5);
            ftc.enable_recognition = cfg.GetBool(sec, "recognize", false);
            ftc.use_rga_backend    = cfg.GetBool(sec, "rga", true);   // RGA 后端更快, 占 dma-heap
            ctx->face_tracker.reset(new FaceTracker());
            if (!ctx->face_tracker->Init(ftc)) {
                HW_ERR("app: pipeline[%s] 人脸追踪初始化失败 (%s)", pname.c_str(),
                       ftc.pack_path.c_str());
                return 3;
            }
            if (ftc.enable_recognition) {
                if (!face_gallery) {
                    face_gallery = std::make_unique<FaceGallery>();
                    const std::string db = cfg.GetStr(sec, "feature_db", "data/faces.db");
                    const float threshold = cfg.GetFloat(sec, "recognize_threshold", 0.48f);
                    if (!face_gallery->Init(db, threshold)) {
                        HW_ERR("app: 人脸特征库初始化失败: %s", db.c_str());
                        return 3;
                    }
                }
                ctx->face_gallery = face_gallery.get();
                ctx->known_person_id = cfg.GetInt(sec, "known_person_id", 1);
                ctx->known_person_name = cfg.GetStr(sec, "known_person_name", "HJ");
            }
            ctx->fusion  = &fusion;
            ctx->overlay = overlay_chs[cam_name].get();
            ctx->status  = &status_ch;
            HW_LOG("app: pipeline[%s] 人脸链就绪 (pack=%s, level=%d)", pname.c_str(),
                   ftc.pack_path.c_str(), ftc.detect_level);
        } else {
            // 占位链(RGA letterbox, 给人脸 SDK 预留输入)
            const int pre = 192;
            if (!dma_buf_alloc_auto((size_t)pre * pre * 3, &ctx->pre_buf)) {
                HW_ERR("app: pipeline[%s] 预处理缓冲分配失败", pname.c_str());
                return 3;
            }
            ctx->pre_img = RgaImage::Rgb888(ctx->pre_buf.fd, ctx->pre_buf.va, pre, pre);
        }

        ctx->kind = type;
        PipeCtx* c = ctx.get();
        pipe->SetFrameHandler([c, pname](FrameHub::FramePtr& fp) -> bool {
            const CameraFrame& f = *fp;
            RgaImage src = RgaImage::Nv12(f.dmabuf_fd, f.vaddr, f.width, f.height, f.wstride);

            // ---- 人脸链: 检测/追踪 → 叠加数据 + 身份观测 ----
            if (c->face_tracker) {
                if (c->next_face_infer_us && f.timestamp_us < c->next_face_infer_us)
                    return true;
                if (!c->next_face_infer_us)
                    c->next_face_infer_us = f.timestamp_us + c->face_infer_interval_us;
                else {
                    c->next_face_infer_us += c->face_infer_interval_us;
                    if (c->next_face_infer_us <= f.timestamp_us)
                        c->next_face_infer_us = f.timestamp_us + c->face_infer_interval_us;
                }
                c->face_inferred.fetch_add(1, std::memory_order_relaxed);

                // 检测+特征提取一次几十 ms: 先把整帧 RGA 复制到本管线私有缓冲, 立刻归还
                // VI 帧, 再在副本上推理 —— 否则识别期间采集无缓冲可用, 实测 face_cam
                // 从 30 FPS 掉到 ~26 FPS(见 docs/board-player-cpu-2026-09-24.md)。
                RgaImage infer_src      = src;
                const size_t copy_bytes = (size_t)f.wstride * f.height * 3 / 2;
                if (c->infer_copy.fd < 0) {
                    if (!dma_buf_alloc_auto(copy_bytes, &c->infer_copy) &&
                        !c->infer_copy_warned) {
                        HW_WARN("pipeline[%s]: 识别副本缓冲分配失败(%zu B), 就地推理",
                                pname.c_str(), copy_bytes);
                        c->infer_copy_warned = true;
                    }
                }
                if (c->infer_copy.fd >= 0 && c->infer_copy.size >= copy_bytes) {
                    const RgaImage copy = RgaImage::Nv12(c->infer_copy.fd, c->infer_copy.va,
                                                         f.width, f.height, f.wstride);
                    if (RgaConvert(src, copy)) {
                        infer_src = copy;
                        fp.reset();   // 像素已在副本里, 提前归还采集缓冲
                    } else if (c->infer_copy_errors++ == 0) {
                        HW_WARN("pipeline[%s]: 识别帧复制失败, 退回就地推理", pname.c_str());
                    }
                }
                std::vector<FaceBox> faces;
                if (!c->face_tracker->Process(infer_src, &faces)) return false;

                OverlayData od;
                od.ts_us = f.timestamp_us;
                int best_track = -1;
                for (const auto& fb : faces) {
                    OverlayData::Face of;
                    of.x1       = fb.x1;
                    of.y1       = fb.y1;
                    of.x2       = fb.x2;
                    of.y2       = fb.y2;
                    of.track_id = fb.track_id;
                    of.score    = fb.score;
                    od.faces.push_back(of);
                    if (best_track < 0) best_track = fb.track_id;
                }
                int matched_id = -1;
                float similarity = 0.f;
                if (faces.size() == 1 && c->face_gallery && !faces[0].feature.empty()) {
                    int64_t candidate = -1;
                    if (c->face_gallery->Search(faces[0].feature, &candidate, &similarity) &&
                        candidate == c->known_person_id) matched_id = (int)candidate;
                }
                if (matched_id != c->face_candidate) {
                    c->face_candidate = matched_id;
                    c->face_candidate_frames = matched_id >= 0 ? 1 : 0;
                } else if (matched_id >= 0 && c->face_candidate_frames < 3) {
                    ++c->face_candidate_frames;
                }
                const int recognized_id = c->face_candidate_frames >= 3 ? matched_id : -1;
                c->last_recognized_id.store(recognized_id);
                if (recognized_id >= 0) {
                    od.faces[0].name = c->known_person_name;
                }
                if (recognized_id != c->face_logged_id) {
                    HW_LOG("pipeline[%s]: 人脸身份 %s id=%d score=%.3f",
                           pname.c_str(), recognized_id >= 0 ? "已确认" : "未确认",
                           recognized_id, similarity);
                    c->face_logged_id = recognized_id;
                }
                if (c->overlay) c->overlay->Publish(od);

                if (c->fusion) {
                    IdentityObservation io;
                    io.ts_us      = f.timestamp_us;
                    io.present    = !faces.empty();
                    io.person_id  = recognized_id;
                    if (recognized_id >= 0) io.name = c->known_person_name;
                    io.similarity = recognized_id >= 0 ? similarity : 0.f;
                    c->fusion->OnIdentity(io);
                }
                if (c->status) {
                    StatusData st = c->status->Snapshot();
                    st.faces_now  = (int)faces.size();
                    if (best_track >= 0) st.last_track = best_track;
                    c->status->Publish(st);
                }
                c->last_det_count.store((int)faces.size());   // 健康统计里显示人脸数
                c->last_det_ts_us.store(hwtime::now_us());
                return true;
            }

            if (!c->detector) {
                // 占位链(未配置推理): RGA letterbox 黑边(与 BORDER_ZERO 一致)
                return RgaLetterbox(src, c->pre_img, 0x00000000u);
            }

            // ---- 1) 手掌检测 ----
            std::vector<HandBox> boxes;
            if (!c->detector->Process(src, &boxes)) return false;
            c->last_det_count.store((int)boxes.size());
            c->last_det_ts_us.store(hwtime::now_us());

            const int phase = c->hand_phase ? c->hand_phase->load(std::memory_order_acquire) : 0;
            if (phase != c->last_hand_phase) {
                c->slots->Reset();
                c->stgcn->Reset();
                c->last_hand_phase = phase;
                HW_LOG("pipeline[%s]: 七步动作推理 %s (phase=%d)", pname.c_str(),
                       phase ? "开启" : "停止", phase);
            }
            if (phase == 0) return true;

            // ---- 2) 每只手: ROI 关键点(21 点) ----
            OverlayData od;
            od.ts_us = f.timestamp_us;
            SlotCandidate cands[2];
            int nh = 0;
            if (!boxes.empty() && c->landmarker->Prepare(src)) {
                for (size_t b = 0; b < boxes.size() && nh < 2; ++b) {
                    HandLandmarks res;
                    if (!c->landmarker->Process(boxes[b], &res)) continue;
                    std::memcpy(c->cand_pts[nh], res.pts, sizeof(res.pts));
                    std::memcpy(c->cand_world[nh], res.world, sizeof(res.world));
                    cands[nh].pts   = c->cand_pts[nh];
                    cands[nh].world = c->cand_world[nh];   // 米制 world(scene3d/world3d 用)
                    cands[nh].side  = res.side();

                    OverlayData::Hand oh;
                    oh.box      = boxes[b];
                    oh.lm       = res;
                    oh.has_lm   = true;
                    oh.lm_valid = res.presence >= c->presence_thresh;
                    // 展示分数用 presence: 检测模型的 score 被量化截断(上限 0.5, 见 docs)
                    oh.score    = res.presence;
                    oh.side     = res.side();
                    od.hands.push_back(oh);
                    ++nh;
                }
            }
            // 没算出关键点的框也要画出来
            for (size_t b = (size_t)nh; b < boxes.size() && od.hands.size() < 2; ++b) {
                OverlayData::Hand oh;
                oh.box    = boxes[b];
                oh.score  = boxes[b].score;
                od.hands.push_back(oh);
            }
            if (c->overlay) c->overlay->Publish(od);

            // 页面可能在关键点推理期间离开教学，避免把越界帧送进动作窗口。
            if (c->hand_phase && c->hand_phase->load(std::memory_order_acquire) != phase)
                return true;

            // ---- 3) 42 点稳定槽位(左右手) → STGCN 滑窗 ----
            float   coords[42][3], world42[42][3];
            uint8_t vis[42];
            c->slots->Assign(cands, nh, (int64_t)(f.timestamp_us / 1000), coords, world42, vis);

            float norm[42][3];
            for (int k = 0; k < 42; ++k) {
                norm[k][0] = coords[k][0] / (float)f.width;
                norm[k][1] = coords[k][1] / (float)f.height;
                norm[k][2] = coords[k][2];
            }
            StgcnWindowResult wres;
            if (c->stgcn->PushFrame(norm, vis, world42, &wres)) {
                ActionObservation obs;
                obs.ts_us        = f.timestamp_us;
                obs.step         = wres.argmax + 1;      // 1..7
                obs.confidence   = wres.conf;
                obs.hand_present = nh > 0;
                if (c->fusion && (!c->hand_phase ||
                    c->hand_phase->load(std::memory_order_acquire) == phase))
                    c->fusion->OnAction(obs);
                c->windows++;
                // 引导页右下轻提示用: 最近一个窗口结果(不稳时显示层会自行去抖)
                c->last_step.store(obs.step, std::memory_order_relaxed);
                c->last_step_conf.store(obs.confidence, std::memory_order_relaxed);
                c->last_step_ts_us.store(hwtime::now_us(), std::memory_order_relaxed);

                if (c->status) {
                    StatusData st  = c->status->Snapshot();
                    st.step        = obs.step;
                    st.conf        = obs.confidence;
                    st.step_ts_us  = obs.ts_us;
                    st.windows     = c->windows.load();
                    c->status->Publish(st);
                }
                HW_LOG("pipeline[%s]: STGCN 窗口 #%d → Step_%d (%.3f)", pname.c_str(),
                       c->windows.load(), obs.step, obs.confidence);
            }
            return true;
        });
        if (!pipe->Init()) return 3;

        HW_LOG("app: pipeline[%s] = %s (camera=%s, %d FPS)", pname.c_str(), type.c_str(),
               cam_name.c_str(), process_fps);
        ctxs.push_back(std::move(ctx));
        pipes.push_back(std::move(pipe));
    }
    if (pipes.empty()) HW_WARN("app: 配置里没有任何 [pipeline.*], 只跑相机");

    // ---- 3b) 屏幕显示(可选): LVGL 宿主 + 首页或双摄调试窗 ----
    //   debug 视频窗是 hub 订阅者，回调只做 RGA + 置脏标志；首页只读检测数量。
    //   LVGL 的一切调用都在主循环(显示线程)完成。
    std::vector<std::unique_ptr<hwdisplay::VideoPane>>   panes;
    std::vector<std::unique_ptr<FrameHub::Subscription>> pane_subs;
    // 每格的绑定关系: 视频窗 + 本路的叠加通道 + 叠加层(手部/人脸)
    struct PaneBinding {
        hwdisplay::VideoPane*                   pane = nullptr;
        handwash::OverlayChannel*               ch   = nullptr;
        std::unique_ptr<hwdisplay::HandOverlay> hov;
        std::unique_ptr<hwdisplay::FaceOverlay> fov;
    };
    std::vector<PaneBinding> pane_bindings;
    std::unique_ptr<hwdisplay::StatusPanel> status_panel;
    std::unique_ptr<hwdisplay::ui::HomeController> home_controller;
    std::unique_ptr<PreviewBuffer> face_preview;
    std::unique_ptr<FrameHub::Subscription> face_preview_sub;   // 人脸取景独立订阅(不被识别阻塞)
    std::unique_ptr<PreviewBuffer> hand_preview;                // 引导页七步教学的俯拍手部取景
    std::unique_ptr<FrameHub::Subscription> hand_preview_sub;
    std::unique_ptr<hwdisplay::ui::FlowController> flow_controller;
    std::unique_ptr<hwdisplay::BoardVideoPlayer> video_player;
    hwdisplay::BoardAnimationCatalog animation_catalog;
    hwdisplay::BoardVideoPlayer::Config video_config;
    std::string current_media;
    hwdisplay::ui::FlowConfig flow_config;
    bool auto_mode = false;
    bool video_started = false;
    bool      display_on = false;
    const std::string display_mode = cfg.GetStr("display", "mode", "home");
    lv_obj_t* status_lbl = nullptr;
    double    cpu_percent = 0;
    flow_config.guide_step_duration_ms = static_cast<uint32_t>(
        std::clamp(cfg.GetInt("display", "step_seconds", 15), 1, 120) * 1000);

    // 引导页(七步教学)俯拍手部取景: 独立订阅 hand_cam, 只在 Guide 场景活跃。
    // 与首页人脸取景同套路: 回调只做 RGA→画布, 不占推理管线的投递。
    auto setup_hand_preview = [&]() {
        std::string hand_cam_name;
        for (const auto& ctx : ctxs)
            if (ctx->kind == "hand") { hand_cam_name = ctx->cam_name; break; }
        if (hand_cam_name.empty()) return;
        auto hub_it = hubs.find(hand_cam_name);
        if (hub_it == hubs.end()) return;
        hand_preview = std::make_unique<PreviewBuffer>();
        const bool mirror = cfg.GetBool("camera." + hand_cam_name, "display_mirror", true);
        // 填充色 = 相机卡底色 0x203F41(flow_view)的 BGRA 字节序
        if (!hand_preview->Init(hwdisplay::ui::FlowView::kCameraWidth,
                                hwdisplay::ui::FlowView::kCameraHeight, mirror, 0xFF413F20u)) {
            HW_WARN("app: 手部取景缓冲分配失败");
            hand_preview.reset();
            return;
        }
        const int fps = std::clamp(cfg.GetInt("display", "hand_preview_fps", 15), 1, 30);
        PreviewBuffer* buf = hand_preview.get();
        hand_preview_sub = hub_it->second->Subscribe(
            "hand-preview", fps, [buf](FrameHub::FramePtr fp) { if (fp) buf->Push(*fp); });
        HW_LOG("app: 引导页手部取景就绪 (独立订阅 %d FPS, mirror=%d)", fps,
               hand_preview->mirror ? 1 : 0);
    };

    auto prepare_video = [&]() {
        const std::string media_dir = cfg.GetStr("display", "media_dir",
            "/mnt/sdcard/handwash-media");
        if (!animation_catalog.Load(media_dir))
            HW_WARN("app: 教学素材清单不可用: %s/catalog.tsv", media_dir.c_str());
        video_config.source_width = static_cast<uint32_t>(
            cfg.GetInt("display", "video_width", 392));
        video_config.source_height = static_cast<uint32_t>(
            cfg.GetInt("display", "video_height", 260));
        video_config.output_width = hwdisplay::ui::FlowView::kVideoWidth;
        video_config.output_height = hwdisplay::ui::FlowView::kVideoHeight;
        video_config.fps = static_cast<uint32_t>(cfg.GetInt("display", "video_fps", 20));
        video_player = std::make_unique<hwdisplay::BoardVideoPlayer>();
        const std::string first = animation_catalog.PathFor("inner");
        if (!first.empty() && video_player->Open(first, video_config)) {
            current_media = "inner";  // 摄像头占用 DMA 堆前预载首段
        } else {
            HW_WARN("app: 无法预载教学素材 id=inner path=%s", first.c_str());
        }
        HW_LOG("app: 教学播放器就绪 (%u fps, %s)", video_config.fps, media_dir.c_str());
    };

    if (cfg.GetBool("display", "enabled", false)) {
        if (!hwdisplay::Init()) {
            HW_WARN("app: 显示初始化失败, 本次不带屏运行");
        } else {
            const std::string& mode = display_mode;
            auto_mode = mode == "auto";
            if (mode == "home" || auto_mode) {
                std::string face_cam_name;
                for (const auto& ctx : ctxs)
                    if (ctx->kind == "face") { face_cam_name = ctx->cam_name; break; }
                if (!face_cam_name.empty()) {
                    face_preview = std::make_unique<PreviewBuffer>();
                    const bool mirror = cfg.GetBool("camera." + face_cam_name,
                                                    "display_mirror", true);
                    // 卡片底色 0x315B69 的 BGRA 字节序
                    if (!face_preview->Init(hwdisplay::ui::HomeView::kFaceWidth,
                                            hwdisplay::ui::HomeView::kFaceHeight, mirror,
                                            0xFF695B31u)) {
                        HW_WARN("app: 人脸预览缓冲分配失败");
                        face_preview.reset();
                    }
                }
                if (face_preview) {
                    const int preview_fps = std::clamp(
                        cfg.GetInt("display", "face_preview_fps", 30), 1, 30);
                    // 取景单独订阅一路: 回调只做 RGA→画布, 与识别管线各自持帧,
                    // 识别那几十毫秒不会再让取景漏帧
                    auto hub_it = hubs.find(face_cam_name);
                    if (hub_it != hubs.end()) {
                        PreviewBuffer* buf = face_preview.get();
                        face_preview_sub = hub_it->second->Subscribe(
                            "face-preview", preview_fps,
                            [buf](FrameHub::FramePtr fp) { if (fp) buf->Push(*fp); });
                    }
                    HW_LOG("app: 人脸取景预览就绪 (独立订阅 %d FPS, mirror=%d)", preview_fps,
                           face_preview->mirror ? 1 : 0);
                }
                setup_hand_preview();   // 引导页俯拍取景(进入 Guide 场景才活跃)
                home_controller = std::make_unique<hwdisplay::ui::HomeController>();
                if (!home_controller->Create(lv_screen_active())) {
                    HW_ERR("app: 首页创建失败，需 800x480 显示屏");
                    return 4;
                }
                if (auto_mode) prepare_video();
                display_on = true;
                HW_LOG("app: 儿童首页就绪 (800x480, %s)",
                       auto_mode ? "识别人脸后自动进入引导" : "无触摸操作");
            } else if (mode == "guide") {
                flow_controller = std::make_unique<hwdisplay::ui::FlowController>(flow_config);
                const uint64_t now_ms = hwtime::now_us() / 1000ULL;
                if (!flow_controller->Create(lv_screen_active(), now_ms)) {
                    HW_ERR("app: 七步引导页创建失败，需 800x480 显示屏");
                    return 4;
                }
                flow_controller->PreviewStep(0, now_ms);
                prepare_video();
                setup_hand_preview();   // guide 模式: 取景就绪(场景即 Guide)
                display_on = true;
                HW_LOG("app: 七步引导播放就绪");
            } else if (mode == "debug") {
                const int   SW = hwdisplay::Width(), SH = hwdisplay::Height();
                const std::string layout = cfg.GetStr("display", "layout", "h");
                const bool  crop = (cfg.GetStr("display", "fit", "letterbox") == "crop");
                const int   dfps = cfg.GetInt("display", "fps", 20);
                const int   top  = cfg.GetInt("display", "top_offset", 0);
                const std::string cn[2] = {cfg.GetStr("display", "pane1", ""),
                                           cfg.GetStr("display", "pane2", "")};

                int main_rc[4] = {0, 0, 0, 0}, sub_rc[4] = {0, 0, 0, 0};
                hwdisplay::LayoutTwoPanes(layout, SW, SH, top, 30, main_rc, sub_rc);
                hwdisplay::LogLvMem("显示初始化后");

                for (int i = 0; i < 2; ++i) {
                    if (cn[i].empty()) continue;
                    auto it = hubs.find(cn[i]);
                    if (it == hubs.end()) {
                        HW_WARN("app: display pane%d 引用了不存在的 camera=%s", i + 1, cn[i].c_str());
                        continue;
                    }
                    const int* rc = (i == 0) ? main_rc : sub_rc;
                    auto pane     = std::make_unique<hwdisplay::VideoPane>();
                    if (!pane->Init(lv_screen_active(), cn[i], rc[0], rc[1], rc[2], rc[3],
                                    crop ? RgaFit::CropCenter : RgaFit::Letterbox))
                        return 4;
                    pane->SetMirror(cfg.GetBool("camera." + cn[i], "display_mirror", true));

                    hwdisplay::VideoPane* pp = pane.get();
                    int dfps_i               = dfps;
                    pane_subs.push_back(it->second->Subscribe(
                        "display:" + cn[i], dfps_i, [pp](FrameHub::FramePtr fp) {
                            if (fp) pp->Push(*fp);
                        }));
                    // 该格相机对应的管线类型 → 决定挂哪种叠加层(手部/人脸)
                    std::string ptype;
                    for (const auto& psec : cfg.Sections("pipeline."))
                        if (cfg.GetStr(psec, "camera", "") == cn[i])
                            ptype = cfg.GetStr(psec, "type", "");

                    PaneBinding b;
                    b.pane = pane.get();
                    b.ch   = overlay_chs[cn[i]].get();
                    if (ptype == "hand") {
                        b.hov = std::make_unique<hwdisplay::HandOverlay>();
                        b.hov->Init(pane->obj(), pane.get());
                    } else if (ptype == "face") {
                        b.fov = std::make_unique<hwdisplay::FaceOverlay>();
                        b.fov->Init(pane->obj(), pane.get());
                    }
                    pane_bindings.push_back(std::move(b));
                    panes.push_back(std::move(pane));
                    hwdisplay::LogLvMem((std::string("pane ") + cn[i]).c_str());
                }

                // 底部内容区: 状态区(当前步骤/最近一次会话) + 调试条
                const int content_y = (layout == "v") ? (top + 216 * 2 + 10) : (top + 225 + 6);
                const int content_h = SH - 30 - content_y - 6;
                if (content_h > 80) {
                    status_panel = std::make_unique<hwdisplay::StatusPanel>();
                    status_panel->Init(lv_screen_active(), 8, content_y, SW - 16, content_h);
                }

                // 调试页底部状态栏
                lv_obj_t* bar = lv_obj_create(lv_screen_active());
                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);
                status_lbl = lv_label_create(bar);
                lv_obj_set_style_text_color(status_lbl, lv_color_white(), 0);
                lv_obj_align(status_lbl, LV_ALIGN_LEFT_MID, 4, 0);
                lv_label_set_text(status_lbl, "handwash: starting...");

                display_on = !panes.empty();
                HW_LOG("app: 显示就绪 (layout=%s, %d FPS, %zu 格)", layout.c_str(), dfps,
                       panes.size());
            } else {
                HW_ERR("app: 未知 display.mode=%s (使用 auto、home、guide 或 debug)", mode.c_str());
                return 4;
            }
        }
    }

    int hand_phase_serial = 0;
    const bool diagnostic_hand_infer = cfg.GetBool("pipeline.hand", "diagnostic_always_infer", false);
    auto update_hand_phase = [&]() {
        const bool guide = diagnostic_hand_infer ||
            (flow_controller && flow_controller->model().scene == hwdisplay::ui::FlowScene::Guide);
        const int previous = hand_phase.load(std::memory_order_acquire);
        if (guide && previous == 0) {
            hand_phase.store(++hand_phase_serial, std::memory_order_release);
        } else if (!guide && previous != 0) {
            hand_phase.store(0, std::memory_order_release);
        }
    };
    update_hand_phase();

    // ---- 4) 启动: 开相机(VI 开始流) → hub(采集) → 管线(订阅) ----
    //   注: 相机放在模型/显示之后打开, 优先保证 NPU 拿到连续内存(见第 1)步说明)
    for (auto& kv : cams) {
        const CameraConfig& cc = cam_cfgs[kv.first];
        if (!kv.second->Open(cc) || !kv.second->Start()) {
            HW_ERR("app: camera[%s] 打开/启动失败", kv.first.c_str());
            return 2;
        }
        std::string extra = cam_is_rockit[kv.first]
                                ? (", pipe=" + std::to_string(cc.pipe_id)) : "";
        HW_LOG("app: camera[%s] = %s (%ux%u%s)", kv.first.c_str(), kv.second->name(), cc.width,
               cc.height, extra.c_str());
    }
    for (auto& kv : hubs) kv.second->Start();
    for (auto& p : pipes) p->Start();
    HW_LOG("app: %zu 路相机 / %zu 路管线运行中%s (Ctrl+C 退出)", hubs.size(), pipes.size(),
           display_on ? " / 屏幕显示开启" : "");

    // ---- 5) 主循环: 显示 tick + 业务/健康统计 ----
    uint64_t t0          = hwtime::now_us();
    uint64_t next_health = t0 + 1000000ULL;
    uint64_t last_health_us = t0;
    uint64_t last_preview_pushed = 0;
    uint64_t last_preview_shown = 0;
    uint64_t last_hand_preview_pushed = 0;
    uint64_t last_hand_preview_shown = 0;
    uint64_t last_face_inferred = 0;
    uint64_t next_fusion = t0 + 500000ULL;
    uint64_t next_status = t0;
    uint64_t unknown_face_since_ms = 0;
    uint64_t hands_only_since_ms = 0;
    // 引导页(Guide)右下轻提示的显示层状态(只归显示线程)
    uint64_t no_hands_since_ms = 0;
    bool     guide_was_active = false;
    hwdisplay::ui::HandFeedback hand_fb_last = hwdisplay::ui::HandFeedback::Observing;
    uint8_t  hand_fb_last_step = 0;
    int      hand_fb_prev_step = 0;
    int      hand_fb_repeat = 0;
    bool auto_armed = true;
    uint64_t auto_absent_since_ms = 0;
    const uint64_t face_wait_ms = static_cast<uint64_t>(
        std::clamp(cfg.GetInt("display", "face_wait_ms", 3000), 500, 10000));

    while (!g_stop) {
        uint64_t now      = hwtime::now_us();
        uint32_t delay_ms = 50;

        if (display_on) {
            if (face_preview && face_preview->TakeDirty()) {
                std::lock_guard<std::mutex> lock(face_preview->pixels_mutex);
                const auto* pixels = static_cast<const uint8_t*>(face_preview->pixels.va);
                if (home_controller) {
                    home_controller->ShowFaceFrame(pixels, face_preview->pixels.size);
                    face_preview->shown.fetch_add(1, std::memory_order_relaxed);
                } else if (flow_controller &&
                           flow_controller->model().scene == hwdisplay::ui::FlowScene::Detecting) {
                    flow_controller->ShowFaceFrame(pixels, face_preview->pixels.size);
                    face_preview->shown.fetch_add(1, std::memory_order_relaxed);
                }
            }
            // 引导页俯拍手部取景: 管线线程已把 NV12→画布转好, 这里只拷贝到 LVGL 画布
            if (flow_controller && hand_preview && hand_preview->TakeDirty()) {
                std::lock_guard<std::mutex> lock(hand_preview->pixels_mutex);
                const auto* pixels = static_cast<const uint8_t*>(hand_preview->pixels.va);
                flow_controller->ShowCameraFrame(pixels, hand_preview->pixels.size);
                hand_preview->shown.fetch_add(1, std::memory_order_relaxed);
            }
            if (home_controller) {
                int face_count = 0;
                int hand_count = 0;
                std::string known_name;
                for (const auto& ctx : ctxs) {
                    const uint64_t seen_at = ctx->last_det_ts_us.load();
                    if (!seen_at || now < seen_at || now - seen_at > 1500000ULL) continue;
                    const int count = ctx->last_det_count.load();
                    if (ctx->kind == "face") {
                        face_count += count;
                        if (count == 1 && ctx->known_person_id >= 0 &&
                            ctx->last_recognized_id.load() == ctx->known_person_id)
                            known_name = ctx->known_person_name;
                    }
                    else if (ctx->kind == "hand") hand_count += count;
                }
                const uint64_t now_ms = now / 1000ULL;
                const uint64_t preview_at = face_preview
                    ? face_preview->last_success_us.load(std::memory_order_acquire) : 0;
                const bool camera_online = face_preview &&
                    (preview_at ? now < preview_at + 2000000ULL : now < t0 + 2500000ULL);
                home_controller->Update(face_count, hand_count, known_name, now_ms,
                                        camera_online);
                if (face_count == 1 && known_name.empty()) {
                    if (!unknown_face_since_ms) unknown_face_since_ms = now_ms;
                } else {
                    unknown_face_since_ms = 0;
                }
                if (face_count == 0 && hand_count > 0) {
                    if (!hands_only_since_ms) hands_only_since_ms = now_ms;
                } else {
                    hands_only_since_ms = 0;
                }
                if (auto_mode) {
                    if (!auto_armed) {
                        if (face_count == 0 && hand_count == 0) {
                            if (!auto_absent_since_ms) auto_absent_since_ms = now_ms;
                            else if (now_ms - auto_absent_since_ms >= 2000) {
                                auto_armed = true;
                                HW_LOG("app: 已重新等待下一位使用者");
                            }
                        } else {
                            auto_absent_since_ms = 0;
                        }
                    }
                    const bool known = home_controller->presence() ==
                                       hwdisplay::ui::HomePresence::KnownFace;
                    const bool hands_only = face_count == 0 && hands_only_since_ms &&
                        now_ms - hands_only_since_ms >= face_wait_ms &&
                        (home_controller->presence() == hwdisplay::ui::HomePresence::HandsVisible ||
                         home_controller->presence() == hwdisplay::ui::HomePresence::CameraOffline);
                    const bool guest = face_count == 1 && !known && unknown_face_since_ms &&
                                       now_ms - unknown_face_since_ms >= face_wait_ms;
                    if (auto_armed && (known || hands_only || guest)) {
                        auto next = std::make_unique<hwdisplay::ui::FlowController>(flow_config);
                        if (next->Create(lv_screen_active(), now_ms)) {
                            home_controller->Destroy();
                            home_controller.reset();
                            flow_controller = std::move(next);
                            auto_armed = false;
                            auto_absent_since_ms = 0;
                            if (known) flow_controller->RecognizeChild(known_name, now_ms);
                            else flow_controller->Handle(hands_only
                                ? hwdisplay::ui::FlowEvent::HandsOnly
                                : hwdisplay::ui::FlowEvent::FaceUnknown, now_ms);
                            if (face_preview)
                                face_preview->active.store(
                                    flow_controller->model().scene ==
                                    hwdisplay::ui::FlowScene::Detecting);
                            if (hand_preview) hand_preview->active.store(false);   // 教学页才取景
                            HW_LOG("app: 自动进入引导 (%s)", known ? known_name.c_str() : "匿名");
                        }
                    }
                }
            }
            if (flow_controller && video_player) {
                const uint64_t now_ms = now / 1000ULL;
                flow_controller->Tick(now_ms);
                if (face_preview)
                    face_preview->active.store(
                        flow_controller->model().scene == hwdisplay::ui::FlowScene::Detecting);
                if (hand_preview)
                    hand_preview->active.store(
                        flow_controller->model().scene == hwdisplay::ui::FlowScene::Guide);
                const char* media_id = flow_controller->MediaId(now_ms);
                const std::string wanted = media_id ? media_id : "";
                if (wanted.empty() && video_started) {
                    video_player->Close();
                    current_media.clear();
                    video_started = false;
                } else if (!wanted.empty() && wanted != current_media) {
                    current_media = wanted;
                    video_player->Close();
                    const std::string path = animation_catalog.PathFor(wanted);
                    if (path.empty() || !video_player->Open(path, video_config))
                        HW_WARN("app: 无法播放教学素材 id=%s path=%s", wanted.c_str(), path.c_str());
                }
                if (!wanted.empty() && video_player->is_open()) {
                    video_player->Update(now, [&](const uint8_t* bgra, size_t bytes) {
                        flow_controller->ShowVideoFrame(bgra, bytes);
                    });
                    video_started = true;
                }
                if (auto_mode && flow_controller->model().scene == hwdisplay::ui::FlowScene::Idle) {
                    auto next = std::make_unique<hwdisplay::ui::HomeController>();
                    if (next->Create(lv_screen_active())) {
                        flow_controller->Destroy();
                        flow_controller.reset();
                        home_controller = std::move(next);
                        if (face_preview) face_preview->active.store(true);
                        if (hand_preview) hand_preview->active.store(false);
                        unknown_face_since_ms = 0;
                        hands_only_since_ms = 0;
                        HW_LOG("app: 已返回首页");
                    }
                }
            }
            for (auto& p : panes)
                if (p->TakeDirty()) lv_obj_invalidate(p->obj());

            // 引导页(Guide)右下轻提示: 相机异常 → 双手未入镜 → 稳定动作 → 无结论。
            // 动作要连续两个窗口同类且 conf≥0.6 才提示 —— 不把单个推理窗口当结论。
            {
                const bool guide_now =
                    flow_controller &&
                    flow_controller->model().scene == hwdisplay::ui::FlowScene::Guide;
                if (guide_now) {
                    const uint64_t now_ms = now / 1000ULL;
                    int      hand_count = 0;
                    int      obs_step   = 0;
                    float    obs_conf   = 0.f;
                    uint64_t obs_at     = 0;
                    for (const auto& ctx : ctxs) {
                        if (ctx->kind != "hand") continue;
                        const uint64_t seen = ctx->last_det_ts_us.load();
                        if (seen && now >= seen && now - seen <= 1500000ULL)
                            hand_count += ctx->last_det_count.load();
                        obs_step = ctx->last_step.load();
                        obs_conf = ctx->last_step_conf.load();
                        obs_at   = ctx->last_step_ts_us.load();
                    }
                    const uint64_t cam_at = hand_preview
                        ? hand_preview->last_success_us.load(std::memory_order_acquire) : 0;
                    const bool cam_online = cam_at && now < cam_at + 2000000ULL;
                    if (hand_count == 0) {
                        if (!no_hands_since_ms) no_hands_since_ms = now_ms;
                    } else {
                        no_hands_since_ms = 0;
                    }

                    using hwdisplay::ui::HandFeedback;
                    HandFeedback fb         = HandFeedback::Observing;
                    uint8_t      fb_step    = 0;
                    if (!cam_online) {
                        fb = HandFeedback::Offline;
                    } else if (no_hands_since_ms && now_ms - no_hands_since_ms >= 1500) {
                        fb = HandFeedback::Missing;
                    } else if (obs_step > 0 && obs_conf >= 0.6f && obs_at &&
                               now - obs_at <= 2500000ULL) {
                        if (obs_step == hand_fb_prev_step) ++hand_fb_repeat;
                        else                                hand_fb_repeat = 1;
                        hand_fb_prev_step = obs_step;
                        if (hand_fb_repeat >= 2) {
                            fb_step = (uint8_t)obs_step;
                            fb      = (obs_step == flow_controller->model().step + 1)
                                          ? HandFeedback::Matched : HandFeedback::Other;
                        }
                    } else {
                        hand_fb_prev_step = 0;
                        hand_fb_repeat    = 0;
                    }
                    if (!guide_was_active) {   // 刚进教学页: 清掉上一轮的残留提示
                        flow_controller->SetHandFeedback(HandFeedback::Observing, 0);
                        hand_fb_last      = HandFeedback::Observing;
                        hand_fb_last_step = 0;
                    }
                    if (fb != hand_fb_last ||
                        (fb != HandFeedback::Observing && fb_step != hand_fb_last_step)) {
                        flow_controller->SetHandFeedback(fb, fb_step);
                        HW_LOG("app: 引导页提示 → %s (识别=%d, 当前第%d步)", FeedbackName(fb),
                               fb_step, flow_controller->model().step + 1);
                        hand_fb_last      = fb;
                        hand_fb_last_step = fb_step;
                    }
                    guide_was_active = true;
                } else {
                    guide_was_active = false;
                    no_hands_since_ms = 0;
                }
            }

            // 叠加层: 每格取本路的最新结果(手部框/骨架 或 人脸框/ID)
            for (auto& b : pane_bindings) {
                handwash::OverlayData od;
                if (b.ch && b.ch->Take(&od)) {
                    if (b.hov) b.hov->Update(od);
                    if (b.fov) b.fov->Update(od);
                }
            }
            handwash::StatusData sd;
            if (status_panel && status_ch.Take(&sd)) status_panel->Update(sd);

            delay_ms = hwdisplay::Tick();

            if (status_lbl && now >= next_status) {   // debug 状态栏
                cpu_percent = hwdisplay::PollProcessCpu();
                char line[256];
                int  off = 0;
                for (auto& kv : hubs) {
                    off += snprintf(line + off, sizeof(line) - off, "%s %.0f  ",
                                    kv.first.c_str(), kv.second->stats().fps_capture);
                }
                off += snprintf(line + off, sizeof(line) - off, "| ");
                for (auto& p : pipes) {
                    const auto& h = p->health();
                    off += snprintf(line + off, sizeof(line) - off, "%s %.0fFPS %.1fms  ",
                                    p->name(), h.fps_process, h.ms_per_frame);
                }
                snprintf(line + off, sizeof(line) - off, "| cpu %.0f%%", cpu_percent);
                lv_label_set_text(status_lbl, line);
                next_status = now + 1000000ULL;
            }
        }

        update_hand_phase();

        if (now >= next_fusion) {
            fusion.Tick();
            next_fusion = now + 500000ULL;
        }
        if (now >= next_health) {
            const double health_seconds = std::max(0.001, (now - last_health_us) / 1e6);
            last_health_us = now;
            uint64_t face_inferred = 0;
            for (const auto& ctx : ctxs)
                face_inferred += ctx->face_inferred.load(std::memory_order_relaxed);
            HW_LOG("app: face-infer=%.1fFPS hand-phase=%d",
                   (face_inferred - last_face_inferred) / health_seconds,
                   hand_phase.load(std::memory_order_acquire));
            last_face_inferred = face_inferred;
            if (face_preview) {
                const uint64_t pushed = face_preview->pushed.load(std::memory_order_relaxed);
                const uint64_t shown = face_preview->shown.load(std::memory_order_relaxed);
                HW_LOG("app: face-preview convert=%.1fFPS show=%.1fFPS err=%llu active=%d",
                       (pushed - last_preview_pushed) / health_seconds,
                       (shown - last_preview_shown) / health_seconds,
                       (unsigned long long)face_preview->errors.load(std::memory_order_relaxed),
                       face_preview->active.load(std::memory_order_acquire) ? 1 : 0);
                last_preview_pushed = pushed;
                last_preview_shown = shown;
            }
            if (hand_preview) {
                const uint64_t pushed = hand_preview->pushed.load(std::memory_order_relaxed);
                const uint64_t shown = hand_preview->shown.load(std::memory_order_relaxed);
                HW_LOG("app: hand-preview convert=%.1fFPS show=%.1fFPS err=%llu active=%d",
                       (pushed - last_hand_preview_pushed) / health_seconds,
                       (shown - last_hand_preview_shown) / health_seconds,
                       (unsigned long long)hand_preview->errors.load(std::memory_order_relaxed),
                       hand_preview->active.load(std::memory_order_acquire) ? 1 : 0);
                last_hand_preview_pushed = pushed;
                last_hand_preview_shown = shown;
            }
            if (video_player && video_player->is_open()) {
                const auto& vs = video_player->stats();
                HW_LOG("app: video[%s] sent=%llu dec=%llu shown=%llu late=%llu loops=%llu err=%llu",
                       current_media.c_str(), (unsigned long long)vs.sent,
                       (unsigned long long)vs.decoded, (unsigned long long)vs.shown,
                       (unsigned long long)vs.late, (unsigned long long)vs.loops,
                       (unsigned long long)vs.errors);
            }
            for (size_t i = 0; i < pipes.size(); ++i) {
                auto&       p  = pipes[i];
                const auto& h  = p->health();
                int         det = ctxs[i]->last_det_count.load();
                HW_LOG("app: [%s] in=%llu proc=%llu err=%llu cap=%.0fFPS proc=%.0fFPS "
                       "frame=%.2fms det=%d",
                       p->name(), (unsigned long long)h.frames_in,
                       (unsigned long long)h.frames_proc, (unsigned long long)h.errors,
                       h.fps_capture, h.fps_process, h.ms_per_frame, det);
            }
            for (auto& kv : hubs) {
                const auto& s = kv.second->stats();
                HW_LOG("app: hub[%s] in=%llu timeout=%llu put=%llu subs=%d cap=%.0fFPS",
                       kv.first.c_str(), (unsigned long long)s.frames_in,
                       (unsigned long long)s.timeouts, (unsigned long long)s.put_back,
                       s.subscribers, s.fps_capture);
            }
            next_health = now + 1000000ULL;
        }

        usleep(delay_ms * 1000);
        if (run_seconds > 0 && hwtime::now_us() - t0 >= (uint64_t)run_seconds * 1000000ULL)
            break;
    }

    // ---- 6) 逆序停止: 先退订显示/管线, 再停采集, 最后关相机 ----
    HW_LOG("app: 停止中...");
    pane_subs.clear();         // 退订显示(不再写画布)
    face_preview_sub.reset();  // 退订取景
    hand_preview_sub.reset();  // 退订引导页取景
    for (auto& p : pipes) p->Stop();
    for (auto& p : pipes) p->Join();
    for (auto& kv : hubs) {
        kv.second->Stop();
        kv.second->Join();
    }
    panes.clear();
    video_player.reset();
    if (flow_controller) flow_controller->Destroy();
    if (home_controller) home_controller->Destroy();
    for (auto& kv : cams) {
        kv.second->Stop();
        kv.second->Close();
    }
    HW_LOG("app: 已退出");
    return 0;
}
