// test_stgcn — ST-GCN++(七类) 板端单测 / 对比工具
//
// 两种模式:
//   1) 黄金模式 --windows <dir>:
//      读 <dir>/win_*.bin(已归一化窗口特征 float32 (32,42,C) NHWC, 由 tools/stgcn_ref.py 导出)
//      → 量化 → 推理 → 输出 CSV(file, logits×7, probs×7, pred)
//      用于与 PC 端 PyTorch logits 逐窗口比对, 隔离"转换+推理"误差
//   2) 端到端 --seq-coords <coords.bin> --seq-visible <visible.bin> [--seq-world <world.bin>]:
//      读整段骨架(coords (T,42,3) float32 / visible (T,42) uint8 / world (T,42,3))
//      → 板端自己 构造特征+滑窗(32/8)+推理+softmax+视频级平均 → 输出汇总
//      --feature image2d|world3d|scene3d 选特征构造(缺省: 给了 world 就是 world3d)
//
// 用法:
//   test_stgcn <model.rknn> --windows <dir> [--n N] [--csv out.csv]
//   test_stgcn <model.rknn> --seq-coords f1 --seq-visible f2 [--seq-world f3]
//                          [--feature scene3d] [--name VID] [--csv out.csv]
#include "common/log.h"
#include "common/stats.h"
#include "common/time_utils.h"
#include "infer/stgcn.h"

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <dirent.h>
#include <fstream>
#include <string>
#include <vector>

using namespace handwash;

namespace {

constexpr int kFrames   = 32;
constexpr int kVertices = 42;

const char* kLabels[7] = {"Step_1", "Step_2", "Step_3", "Step_4", "Step_5", "Step_6", "Step_7"};

bool read_into(const std::string& path, void* dst, size_t expect) {
    std::ifstream f(path, std::ios::binary | std::ios::ate);
    if (!f) return false;
    if ((size_t)f.tellg() != expect) return false;
    f.seekg(0);
    f.read(static_cast<char*>(dst), (std::streamsize)expect);
    return (bool)f;
}

std::vector<uint8_t> read_all(const std::string& path) {
    std::ifstream f(path, std::ios::binary | std::ios::ate);
    if (!f) return {};
    std::streamsize size = f.tellg();
    if (size <= 0) return {};
    std::vector<uint8_t> buf((size_t)size);
    f.seekg(0);
    f.read(reinterpret_cast<char*>(buf.data()), size);
    return f ? buf : std::vector<uint8_t>{};
}

std::vector<std::string> list_windows(const std::string& dir) {
    std::vector<std::string> out;
    DIR* d = opendir(dir.c_str());
    if (!d) return out;
    while (struct dirent* e = readdir(d)) {
        std::string name = e->d_name;
        if (name.size() > 4 && name.rfind("win_") == 0 && name.substr(name.size() - 4) == ".bin")
            out.push_back(name);
    }
    closedir(d);
    std::sort(out.begin(), out.end());
    return out;
}

bool is_dir(const std::string& path) {
    DIR* d = opendir(path.c_str());
    if (d) { closedir(d); return true; }
    return false;
}

// ---------------- 黄金模式 ----------------

int run_windows_mode(Stgcn& stgcn, const std::string& dir, int n, const std::string& csv_path) {
    std::vector<std::string> files;
    const bool single_file = !is_dir(dir);
    if (single_file) files.push_back(dir);
    else            files = list_windows(dir);
    if (files.empty()) {
        HW_ERR("目录中没有 win_*.bin: %s", dir.c_str());
        return 7;
    }
    if (n > 0 && (int)files.size() > n) files.resize(n);

    std::ofstream csv;
    if (!csv_path.empty()) {
        csv.open(csv_path);
        csv << "file,pred,conf";
        for (int i = 0; i < 7; ++i) csv << ",logit" << i;
        for (int i = 0; i < 7; ++i) csv << ",prob" << i;
        csv << "\n";
    }

    hwstat::Latency lat;
    const size_t expect = (size_t)kFrames * kVertices * stgcn.input_channels() * sizeof(float);
    std::vector<float> feats((size_t)kFrames * kVertices * stgcn.input_channels());
    for (const std::string& name : files) {
        std::string path = single_file ? name : (dir + "/" + name);
        if (!read_into(path, feats.data(), expect)) {
            HW_WARN("跳过 %s (读取失败或尺寸不符, 需要 %zu 字节)", path.c_str(), expect);
            continue;
        }
        StgcnWindowResult res;
        if (!stgcn.InferFeatures(feats.data(), &res)) {
            HW_ERR("%s 推理失败", name.c_str());
            return 6;
        }
        lat.Add(stgcn.last_ms());
        HW_LOG("[win] %-32s pred=%s conf=%.4f  probs=[%.3f %.3f %.3f %.3f %.3f %.3f %.3f]",
               path.c_str(), kLabels[res.argmax], res.conf, res.probs[0], res.probs[1],
               res.probs[2], res.probs[3], res.probs[4], res.probs[5], res.probs[6]);
        if (csv.is_open()) {
            csv << path << "," << kLabels[res.argmax] << "," << res.conf;
            for (int i = 0; i < 7; ++i) csv << "," << res.logits[i];
            for (int i = 0; i < 7; ++i) csv << "," << res.probs[i];
            csv << "\n";
        }
    }
    HW_LOG("黄金模式完成: %zu 窗口, infer avg=%.2fms", files.size(), lat.avg());
    return 0;
}

// ---------------- 端到端模式 ----------------

int run_seq_mode(Stgcn& stgcn, const std::string& coords_path, const std::string& visible_path,
                 const std::string& world_path, const std::string& name,
                 const std::string& csv_path) {
    std::vector<uint8_t> coords_raw = read_all(coords_path);
    std::vector<uint8_t> visible_raw = read_all(visible_path);
    if (coords_raw.empty() || visible_raw.empty()) {
        HW_ERR("读取骨架失败: %s / %s", coords_path.c_str(), visible_path.c_str());
        return 2;
    }
    const size_t frame_coords = kVertices * 3 * sizeof(float);
    const size_t frame_visible = kVertices;
    if (coords_raw.size() % frame_coords || visible_raw.size() % frame_visible) {
        HW_ERR("骨架文件尺寸不合法");
        return 2;
    }
    const int T = (int)(coords_raw.size() / frame_coords);
    if ((size_t)T * frame_visible != visible_raw.size()) {
        HW_ERR("coords/visible 帧数不一致");
        return 2;
    }
    std::vector<uint8_t> world_raw;
    if (!world_path.empty()) {
        world_raw = read_all(world_path);
        if (world_raw.size() != coords_raw.size()) {
            HW_ERR("world 文件尺寸不匹配");
            return 2;
        }
    }

    std::ofstream csv;
    if (!csv_path.empty()) {
        csv.open(csv_path);
        csv << "window,start_frame,pred,conf";
        for (int i = 0; i < 7; ++i) csv << ",logit" << i;
        for (int i = 0; i < 7; ++i) csv << ",prob" << i;
        csv << "\n";
    }

    const float* coords_all = reinterpret_cast<const float*>(coords_raw.data());
    const float* world_all  = world_raw.empty() ? nullptr : reinterpret_cast<const float*>(world_raw.data());

    hwstat::Latency lat;
    int wins = 0;
    for (int t = 0; t < T; ++t) {
        float coords[42][3], world[42][3];
        std::memcpy(coords, coords_all + (size_t)t * kVertices * 3, sizeof(coords));
        if (world_all) std::memcpy(world, world_all + (size_t)t * kVertices * 3, sizeof(world));
        const uint8_t* visible = visible_raw.data() + (size_t)t * kVertices;
        StgcnWindowResult res;
        if (stgcn.PushFrame(coords, visible, world_all ? world : nullptr, &res)) {
            lat.Add(stgcn.last_ms());
            if (csv.is_open()) {
                csv << wins << "," << res.start_frame << "," << kLabels[res.argmax] << "," << res.conf;
                for (int i = 0; i < 7; ++i) csv << "," << res.logits[i];
                for (int i = 0; i < 7; ++i) csv << "," << res.probs[i];
                csv << "\n";
            }
            ++wins;
        }
    }
    StgcnWindowResult res;
    if (stgcn.Flush(&res)) {
        lat.Add(stgcn.last_ms());
        if (csv.is_open()) {
            csv << wins << "," << res.start_frame << "," << kLabels[res.argmax] << "," << res.conf;
            for (int i = 0; i < 7; ++i) csv << "," << res.logits[i];
            for (int i = 0; i < 7; ++i) csv << "," << res.probs[i];
            csv << "\n";
        }
        ++wins;
    }

    float mean[7] = {};
    if (!stgcn.MeanProbs(mean, 7)) {
        HW_ERR("无窗口结果");
        return 7;
    }
    int best = 0;
    for (int i = 1; i < 7; ++i) if (mean[i] > mean[best]) best = i;
    HW_LOG("[e2e] video=%s frames=%d windows=%d pred=%s conf=%.4f", name.c_str(), T,
           stgcn.window_count(), kLabels[best], mean[best]);
    HW_LOG("      mean_probs=[%.3f %.3f %.3f %.3f %.3f %.3f %.3f] infer avg=%.2fms",
           mean[0], mean[1], mean[2], mean[3], mean[4], mean[5], mean[6], lat.avg());
    (void)wins;
    return 0;
}

void usage(const char* prog) {
    fprintf(stderr,
            "用法:\n"
            "  %s <model.rknn> --windows <dir> [--n N] [--csv out.csv]\n"
            "  %s <model.rknn> --seq-coords <coords.bin> --seq-visible <visible.bin>\n"
            "                  [--seq-world <world.bin>] [--feature image2d|world3d|scene3d]\n"
            "                  [--name VID] [--csv out.csv]\n",
            prog, prog);
}

}  // namespace

int main(int argc, char** argv) {
    if (argc < 2) {
        usage(argv[0]);
        return 1;
    }
    std::string model = argv[1], windows_dir, coords, visible, world, name = "seq", csv_path;
    int n = 0;
    bool use_world = false;
    std::string feature_name;   // image2d | world3d | scene3d(缺省按 --world 推断)

    for (int i = 2; i < argc; ++i) {
        std::string a = argv[i];
        auto next = [&](const char* what) -> std::string {
            if (i + 1 >= argc) { fprintf(stderr, "缺少参数: %s\n", what); exit(1); }
            return argv[++i];
        };
        if (a == "--windows")        windows_dir = next("--windows");
        else if (a == "--seq-coords")  coords = next("--seq-coords");
        else if (a == "--seq-visible") visible = next("--seq-visible");
        else if (a == "--seq-world") { world = next("--seq-world"); use_world = true; }
        else if (a == "--world")       use_world = true;
        else if (a == "--feature")     feature_name = next("--feature");
        else if (a == "--name")        name = next("--name");
        else if (a == "--n")           n = atoi(next("--n").c_str());
        else if (a == "--csv")         csv_path = next("--csv");
        else { usage(argv[0]); return 1; }
    }

    StgcnConfig cfg;
    cfg.model_path = model;
    if (feature_name == "scene3d")      cfg.feature = StgcnFeature::Scene3d;
    else if (feature_name == "world3d") cfg.feature = StgcnFeature::World3d;
    else if (feature_name == "image2d") cfg.feature = StgcnFeature::Image2d;
    else cfg.feature = use_world ? StgcnFeature::World3d : StgcnFeature::Image2d;
    Stgcn stgcn;
    if (!stgcn.Init(cfg)) {
        HW_ERR("STGCN 模型加载失败: %s", model.c_str());
        return 2;
    }

    if (!windows_dir.empty()) return run_windows_mode(stgcn, windows_dir, n, csv_path);
    if (!coords.empty() && !visible.empty())
        return run_seq_mode(stgcn, coords, visible, world, name, csv_path);
    usage(argv[0]);
    return 1;
}
