#!/usr/bin/env python3
"""A15 V4 自測：用 A36 300 棒官方 fixture 驗證本席實作（可任何人覆核）
用法：
  python3 A15_v4_selftest.py a36_fixture.json
fixture JSON 需含 keys: params / input_bars_ts_o_h_l_c_v / expected_latest / expected_labels
（由 A36_66087_V4_UPSTREAM_PINE_AND_300BAR_FIXTURE.html 內嵌 JSON 抽出）
退出碼：0 = 全部一致；1 = 有差異（列出逐欄 diff）
"""
import json
import sys

import A15_v4_indicator as v4

TOL = 1e-9
FIELDS = [("st", "st"), ("age", "age"), ("convictionPct", "s"),
          ("erSmooth", "er"), ("volRatio", "vol_ratio"),
          ("adaptiveFactor", "adaptive_factor"), ("adaptiveConfirm", "adaptive_confirm"),
          ("flipQuality", "flip_quality"), ("flipGrade", "quality_grade"),
          ("distancePct", "dist_pct"), ("bullFlips", "bull_ct"), ("bearFlips", "bear_ct")]


def main(path: str) -> int:
    F = json.load(open(path, encoding="utf-8"))
    p = F.get("params") or {}
    kw = {}
    if "atrLen" in p:      kw["i_len"] = p["atrLen"]
    if "baseFactor" in p:  kw["i_factor"] = p["baseFactor"]
    if "erLen" in p:       kw["i_er_len"] = p["erLen"]
    if "confirmBars" in p: kw["i_confirm"] = p["confirmBars"]
    bars = [dict(t=r[0], o=r[1], h=r[2], l=r[3], c=r[4], v=r[5])
            for r in F["input_bars_ts_o_h_l_c_v"]]
    rows = v4.compute(bars, **kw)
    scored = [r for r in rows if r]
    last = scored[-1]
    exp = F["expected_latest"]

    bad = 0
    print(f"bars={len(bars)} scored={len(scored)}")
    for exp_key, my_key in FIELDS:
        e, g = exp.get(exp_key), last.get(my_key)
        if my_key == "s":
            g = round(g * 100)          # 上游 conviction 用百分比整數
        if isinstance(e, (int, float)) and isinstance(g, (int, float)):
            ok = abs(float(e) - float(g)) <= TOL
        else:
            ok = (e == g)
        bad += 0 if ok else 1
        print(f"  {'OK ' if ok else 'DIFF'} {exp_key:<18} exp={e!r:<24} got={g!r}")

    direction_ok = (exp.get("direction") == "LONG") == (last["dir"] == 1)
    bad += 0 if direction_ok else 1
    print(f"  {'OK ' if direction_ok else 'DIFF'} direction          exp={exp.get('direction')} got={'LONG' if last['dir']==1 else 'SHORT'}")

    flips = [(i, r) for i, r in enumerate(rows) if r and r["any_flip"]]
    exp_labels = F.get("expected_labels") or []
    got_labels = [(i, "SHORT" if r["flip_down"] else "LONG", r["quality_grade"], r["flip_quality"])
                  for i, r in flips]
    exp_pairs = [(l["barIndex"], l["direction"], l["grade"], l["quality"]) for l in exp_labels]
    labels_ok = got_labels == exp_pairs
    bad += 0 if labels_ok else 1
    print(f"  {'OK ' if labels_ok else 'DIFF'} labels             exp={exp_pairs} got={got_labels}")

    print("RESULT:", "PASS (0 diff)" if bad == 0 else f"FAIL ({bad} diff)")
    return 0 if bad == 0 else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "a36_fixture.json"))
