// StreamPipeline 实现 — 向 FrameHub 订阅, 在订阅线程里跑 handler(推理链)
#include "pipeline/stream_pipeline.h"

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

namespace handwash {

StreamPipeline::StreamPipeline(std::string name, FrameHub* hub, Config cfg)
    : name_(std::move(name)), hub_(hub), cfg_(cfg) {}

StreamPipeline::~StreamPipeline() {
    Stop();
    Join();
}

bool StreamPipeline::Init() {
    if (!hub_) {
        HW_ERR("pipeline[%s]: 帧分发中枢为空", name_.c_str());
        return false;
    }
    // 采集由 hub 统一负责(唯一采集线程), 本管线只订阅自己需要的帧率
    HW_LOG("pipeline[%s]: 订阅 hub[%s] (%s), 处理帧率=%d FPS", name_.c_str(),
           hub_->name().c_str(), hub_->source() ? hub_->source()->name() : "?",
           cfg_.process_fps);
    return true;
}

bool StreamPipeline::Start() {
    if (sub_) return true;
    if (!hub_) return false;

    win_start_us_ = hwtime::now_us();
    sub_ = hub_->Subscribe(name_, cfg_.process_fps, [this](FrameHub::FramePtr fp) {
        if (!fp) return;
        health_.frames_in++;
        health_.frames_proc++;
        win_proc_++;

        if (handler_) {
            double t0 = hwtime::now_ms();
            if (!handler_(*fp)) health_.errors++;
            double dt = hwtime::now_ms() - t0;
            health_.ms_per_frame =
                health_.ms_per_frame == 0 ? dt : health_.ms_per_frame * 0.9 + dt * 0.1;
        }

        // 每秒刷新处理帧率(采集帧率直接取 hub 的统计)
        uint64_t now = hwtime::now_us();
        if (now - win_start_us_ >= 1000000ULL) {
            double d = (double)(now - win_start_us_) / 1e6;
            health_.fps_process = d > 0 ? (double)win_proc_ / d : 0;
            health_.fps_capture = hub_->stats().fps_capture;
            win_proc_     = 0;
            win_start_us_ = now;
        }
    });
    if (!sub_) {
        HW_ERR("pipeline[%s]: 订阅失败", name_.c_str());
        return false;
    }
    return true;
}

void StreamPipeline::Stop() { sub_.reset(); }   // 退订(会 join 本管线的订阅线程)

void StreamPipeline::Join() {}                  // 退订时已完成 join
}  // namespace handwash
