/* sound-core.test.js — 声音树自检（Node 运行，无 DOM、无定时器）
 *
 * 两类测试：
 *  1) 纯函数单元测试：RMS、阈值分级、树生长状态机
 *  2) 真实 WAV 校验：直接解析 inputs/calibration.wav 的 PCM 数据，
 *     按 spec.json 的分段计算真实 RMS，验证分级与 spec 声明一致
 *
 * 运行：node sound-core.test.js
 */
"use strict";

var fs = require("fs");
var path = require("path");
var SoundCore = require("./sound-core.js");

var passed = 0;
var failed = 0;

function check(name, actual, expected) {
  var ok = Object.is(actual, expected);
  if (ok) {
    passed++;
    console.log("  PASS  " + name + "  (actual=" + actual + ")");
  } else {
    failed++;
    console.log("  FAIL  " + name + "  expected=" + expected + " actual=" + actual);
  }
}

function checkNear(name, actual, expected, eps) {
  var ok = Math.abs(actual - expected) <= eps;
  if (ok) {
    passed++;
    console.log(
      "  PASS  " + name + "  (actual=" + actual.toFixed(6) + " ≈ " + expected + ")"
    );
  } else {
    failed++;
    console.log(
      "  FAIL  " + name + "  expected≈" + expected + " actual=" + actual
    );
  }
}

/* ---------- 1. computeRMS ---------- */
console.log("[1] computeRMS 纯函数");
check(
  "空样本 -> 0",
  SoundCore.computeRMS(new Float32Array(0)),
  0
);
check(
  "全零 -> 0",
  SoundCore.computeRMS(new Float32Array([0, 0, 0, 0])),
  0
);
checkNear(
  "[0.5,-0.5] -> 0.5",
  SoundCore.computeRMS(new Float32Array([0.5, -0.5])),
  0.5,
  1e-12
);
checkNear(
  "[0.3] -> ≈0.3（Float32 存储精度）",
  SoundCore.computeRMS(new Float32Array([0.3])),
  0.3,
  1e-7
);
checkNear(
  "[3,4] -> √12.5 ≈ 3.5355",
  SoundCore.computeRMS(new Float32Array([3, 4])),
  Math.sqrt(12.5),
  1e-12
);

/* ---------- 2. classify：阈值边界严格按 spec ---------- */
console.log("[2] classify 阈值边界 (quietBelow=0.01, loudAtLeast=0.1)");
check("0.000  -> quiet", SoundCore.classify(0.0), "quiet");
check("0.0099 -> quiet", SoundCore.classify(0.0099), "quiet");
check("0.010  -> soft （恰好在 quietBelow，不算安静）", SoundCore.classify(0.01), "soft");
check("0.0101 -> soft", SoundCore.classify(0.0101), "soft");
check("0.099  -> soft", SoundCore.classify(0.099), "soft");
check("0.100  -> loud （恰好在 loudAtLeast）", SoundCore.classify(0.1), "loud");
check("0.200  -> loud", SoundCore.classify(0.2), "loud");
check(
  "阈值可注入",
  SoundCore.classify(0.05, { quietBelow: 0.06, loudAtLeast: 0.2 }),
  "quiet"
);

/* ---------- 3. updateTree 状态机 ---------- */
console.log("[3] updateTree 生长状态机（纯函数）");
var t0 = SoundCore.createTree();
check("初始 progress=0", t0.progress, 0);
check("初始 stage=种子", t0.stage, "种子");
check("初始 leaves=0", t0.leaves, 0);

var frozen = SoundCore.createTree();
var tA = SoundCore.updateTree(frozen, "loud", 1);
checkNear("响亮 1s -> progress +20", tA.progress, 20, 1e-9);
check("响亮 1s -> mood=bright", tA.mood, "bright");
checkNear("输入对象未被修改（不可变）", frozen.progress, 0, 1e-12);

var tB = SoundCore.updateTree(tA, "soft", 1);
checkNear("再轻声 1s -> progress +8", tB.progress, 28, 1e-9);
check("轻声 1s -> mood=gentle", tB.mood, "gentle");

var tC = SoundCore.updateTree(tB, "quiet", 1);
checkNear("安静 1s -> progress -3", tC.progress, 25, 1e-9);
check("安静 1s -> mood=folded", tC.mood, "folded");

var tD = SoundCore.updateTree(tC, "quiet", 100);
check("安静 100s -> progress 触底 0 不为负", tD.progress, 0);

var tE = tD;
for (var i = 0; i < 6; i++) tE = SoundCore.updateTree(tE, "loud", 1);
checkNear("响亮 6s -> progress 封顶 100", tE.progress, 100, 1e-9);
check("封顶 -> stage=繁茂", tE.stage, "繁茂");
check("封顶 -> leaves=24（全部叶子）", tE.leaves, SoundCore.TOTAL_LEAVES);

var tF = SoundCore.updateTree(SoundCore.updateTree(SoundCore.createTree(), "soft", 5), null, 1);
checkNear("暂停（level=null）-> progress 不变", tF.progress, 40, 1e-9);

checkNear(
  "阶段边界：progress=40 -> 幼苗",
  (function () {
    var t = SoundCore.createTree();
    t.progress = 40;
    return SoundCore.updateTree(t, null, 0).stage === "幼苗" ? 1 : 0;
  })(),
  1,
  1e-12
);

/* ---------- 4. 真实 WAV 校验（不做任何模拟，直接读 PCM） ---------- */
console.log("[4] 真实解析 inputs/calibration.wav，按 spec 分段验证 RMS");

var spec = JSON.parse(
  fs.readFileSync(path.join(__dirname, "..", "inputs", "spec.json"), "utf8")
);
var wavPath = path.join(__dirname, "..", "inputs", "calibration.wav");
var buf = fs.readFileSync(wavPath);

// 手工解析 WAV 头（16-bit PCM 单声道）
var fmtTag = buf.readUInt16LE(20);
var channels = buf.readUInt16LE(22);
var sampleRate = buf.readUInt32LE(24);
var bitsPerSample = buf.readUInt16LE(34);
check("WAV 编码为 PCM(1)", fmtTag, 1);
check("WAV 单声道", channels, 1);
check("WAV 16-bit", bitsPerSample, 16);
console.log("  INFO  sampleRate=" + sampleRate);

var dataIdx = buf.indexOf("data", 12, "ascii");
var dataLen = buf.readUInt32LE(dataIdx + 4);
var nSamples = dataLen / 2;
var samples = new Float32Array(nSamples);
for (var s = 0; s < nSamples; s++) {
  samples[s] = buf.readInt16LE(dataIdx + 8 + s * 2) / 32768;
}
console.log(
  "  INFO  共 " + nSamples + " 样本，时长 " + (nSamples / sampleRate).toFixed(2) + "s"
);

var expectedRms = [0, 0.02, 0.2, 0];
var expectedLevel = ["quiet", "soft", "loud", "quiet"];
spec.segments.forEach(function (seg, idx) {
  var from = Math.round(seg.start * sampleRate);
  var to = Math.round(seg.end * sampleRate);
  var segSamples = samples.subarray(from, to);
  var rms = SoundCore.computeRMS(segSamples);
  var level = SoundCore.classify(rms, spec.rmsThresholds);
  checkNear(
    "段 " + idx + " [" + seg.start + "-" + seg.end + "s] 实测 RMS ≈ spec 声明 " + seg.rms,
    rms,
    expectedRms[idx],
    0.005
  );
  check(
    "段 " + idx + " 分级 = " + expectedLevel[idx],
    level,
    expectedLevel[idx]
  );
});

/* ---------- 汇总 ---------- */
console.log("");
console.log("================================");
console.log("通过 " + passed + " 项，失败 " + failed + " 项");
console.log("================================");
process.exit(failed === 0 ? 0 : 1);
