// FrameHub 实现 — 采集线程 + 每订阅者消费线程(单槽 latest-wins)
#include "pipeline/frame_hub.h"

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

#include <chrono>
#include <future>

namespace handwash {

// ---------------- 订阅者状态(内部) ----------------
struct FrameHub::SubState {
    std::string name;
    int         fps         = 0;    // 0 = 不节流
    uint64_t    interval_us = 0;    // 投递间隔(由 fps 换算)
    uint64_t    next_push   = 0;    // 下一次允许投递的时刻(累计式节流)
    Sink        cb;

    // 单槽(latest-wins)
    std::mutex              mtx;
    std::condition_variable cv;
    FramePtr                slot;
    bool                    has_data = false;

    std::thread       thr;
    std::atomic<bool> run{true};
    SubStats          stats;
    uint64_t          win_start_us = 0;   // fps 统计窗口
    uint64_t          win_count    = 0;
};

// ---------------- Subscription ----------------
FrameHub::Subscription::Subscription(FrameHub* hub, std::shared_ptr<SubState> st)
    : hub_(hub), st_(std::move(st)) {}

FrameHub::Subscription::~Subscription() {
    if (hub_) hub_->Unsubscribe(this);
}

const std::string& FrameHub::Subscription::name() const { return st_->name; }

const FrameHub::SubStats& FrameHub::Subscription::stats() const { return st_->stats; }

// ---------------- FrameHub ----------------
FrameHub::FrameHub(std::string name, FrameSource* src) : name_(std::move(name)), src_(src) {}

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

bool FrameHub::Start() {
    if (!src_) {
        HW_ERR("hub[%s]: 帧源为空", name_.c_str());
        return false;
    }
    bool expect = false;
    if (!running_.compare_exchange_strong(expect, true)) return true;   // 已启动
    thr_ = std::thread(&FrameHub::Loop, this);
    HW_LOG("hub[%s]: 采集线程启动 (%s)", name_.c_str(), src_->name());
    return true;
}

void FrameHub::Stop() {
    if (!running_.exchange(false)) return;
    cv_.notify_all();
    // 通知所有订阅线程退出
    {
        std::lock_guard<std::mutex> lk(list_mutex_);
        for (auto& s : subs_) {
            s->run = false;
            s->cv.notify_all();
        }
    }
}

void FrameHub::Join() {
    if (thr_.joinable()) thr_.join();
    DropAllSubscriptions();
}

void FrameHub::DropAllSubscriptions() {
    std::vector<std::shared_ptr<SubState>> subs;
    {
        std::lock_guard<std::mutex> lk(list_mutex_);
        subs.swap(subs_);
        stats_.subscribers = 0;
    }
    for (auto& s : subs) {
        s->run = false;
        s->cv.notify_all();
        if (s->thr.joinable()) s->thr.join();
        std::lock_guard<std::mutex> lk(s->mtx);
        s->slot.reset();   // 释放可能残留的帧(触发 PutFrame 归还)
        s->has_data = false;
    }
}

void FrameHub::Unsubscribe(Subscription* h) {
    std::shared_ptr<SubState> st = h->st_;
    {
        std::lock_guard<std::mutex> lk(list_mutex_);
        for (auto it = subs_.begin(); it != subs_.end(); ++it) {
            if (it->get() == st.get()) {
                subs_.erase(it);
                break;
            }
        }
        stats_.subscribers = (int)subs_.size();
    }
    st->run = false;
    st->cv.notify_all();
    if (st->thr.joinable()) st->thr.join();
    std::lock_guard<std::mutex> lk(st->mtx);
    st->slot.reset();
    st->has_data = false;
}

std::unique_ptr<FrameHub::Subscription> FrameHub::Subscribe(std::string name, int fps, Sink cb) {
    auto st       = std::make_shared<SubState>();
    st->name      = std::move(name);
    st->fps       = fps;
    st->interval_us = fps > 0 ? (1000000ULL / (uint64_t)fps) : 0;
    st->cb        = std::move(cb);
    st->win_start_us = hwtime::now_us();

    auto* stp = st.get();
    st->thr   = std::thread([this, stp]() {
        while (true) {
            FramePtr fp;
            {
                std::unique_lock<std::mutex> lk(stp->mtx);
                stp->cv.wait(lk, [stp] { return stp->has_data || !stp->run.load(); });
                if (!stp->run.load()) break;
                stp->has_data = false;
                fp            = std::move(stp->slot);
            }
            if (!fp) continue;
            stp->stats.consumed++;
            stp->win_count++;
            if (stp->cb) stp->cb(fp);
            fp.reset();   // 归还(引用计数归零 → PutFrame)

            uint64_t now = hwtime::now_us();
            if (now - stp->win_start_us >= 1000000ULL) {
                double dt     = (double)(now - stp->win_start_us) / 1e6;
                stp->stats.fps = dt > 0 ? (double)stp->win_count / dt : 0;
                stp->win_count = 0;
                stp->win_start_us = now;
            }
        }
    });

    {
        std::lock_guard<std::mutex> lk(list_mutex_);
        subs_.push_back(st);
        stats_.subscribers = (int)subs_.size();
    }
    HW_LOG("hub[%s]: 新订阅 '%s' (fps=%d)", name_.c_str(), st->name.c_str(), fps);
    // 注意: 这里必须直接 new —— 构造函数是 private, 只有 FrameHub(友元)能访问,
    // std::make_unique 的上下文不属于友元, GCC 会报 "is private within this context"
    return std::unique_ptr<Subscription>(new Subscription(this, st));
}

bool FrameHub::SubscribeOnce(int timeout_ms, const Sink& cb) {
    auto done = std::make_shared<std::promise<bool>>();
    auto fut  = done->get_future();
    auto sub  = Subscribe("once", 0, [cb, done](FramePtr f) {
        if (cb) cb(f);
        try { done->set_value(true); } catch (...) {}
    });
    if (!sub) return false;
    bool ok = fut.wait_for(std::chrono::milliseconds(timeout_ms)) == std::future_status::ready;
    sub.reset();   // 退订(join 消费线程)
    return ok && fut.get();
}

void FrameHub::Loop() {
    uint64_t win_start = hwtime::now_us();
    uint64_t win_in    = 0;

    while (running_) {
        CameraFrame f;
        if (!src_->GetFrame(&f, 1000)) {
            if (running_) stats_.timeouts++;
            continue;
        }
        stats_.frames_in++;
        win_in++;

        // 包装成共享句柄: 最后一个引用析构时归还
        FramePtr fp(new CameraFrame(f), [this](const CameraFrame* p) {
            if (src_) src_->PutFrame(*p);
            stats_.put_back++;
            delete p;
        });

        // 快照订阅者列表后立即释放表锁(投递期间不与 Subscribe/Unsubscribe 争锁)
        std::vector<std::shared_ptr<SubState>> subs;
        {
            std::lock_guard<std::mutex> lk(list_mutex_);
            if (subs_.empty()) {
                // 无订阅者: 直接归还(保持数据流&3A 会话稳定, 不做停流)
                fp.reset();
            } else {
                subs = subs_;
            }
        }

        uint64_t now = hwtime::now_us();
        for (auto& s : subs) {
            if (!s->run.load()) continue;
            if (s->interval_us) {
                if (s->next_push == 0) s->next_push = now;
                if (now < s->next_push) {
                    s->stats.dropped++;
                    continue;
                }
                s->next_push += s->interval_us;
                if (now > s->next_push + s->interval_us)   // 落后过多: 重新对齐
                    s->next_push = now + s->interval_us;
            }
            {
                std::lock_guard<std::mutex> lk(s->mtx);
                if (s->has_data) {
                    // 消费者还没取走上一帧: **直接丢弃新帧**, 不覆盖单槽。
                    // 覆盖会让单槽一直占着一块采集缓冲(VI 仅 3 块), 长耗时推理(人脸
                    // 检测+识别上百 ms)期间采集无缓冲可用 → 相机有效帧率下降。
                    // 跳过的帧只影响该订阅者自己(它对时效性的要求由下一次投递满足)。
                    s->stats.dropped++;
                } else {
                    s->slot     = fp;
                    s->has_data = true;
                    s->stats.delivered++;
                    s->cv.notify_one();
                }
            }
        }
        fp.reset();   // 若所有订阅者都已持引用, 这里不触发归还

        // 每秒刷新采集帧率
        if (now - win_start >= 1000000ULL) {
            double dt = (double)(now - win_start) / 1e6;
            stats_.fps_capture = dt > 0 ? (double)win_in / dt : 0;
            win_in    = 0;
            win_start = now;
        }
    }
    HW_LOG("hub[%s]: 采集线程退出 (in=%llu timeout=%llu)", name_.c_str(),
           (unsigned long long)stats_.frames_in, (unsigned long long)stats_.timeouts);
}

}  // namespace handwash
