# -*- coding: utf-8 -*-
"""Stub-runtime harness：exec 交付件 v4_futu_ftnn_hk.py 本身，對 A36 黃金 fixture 3fc8ce27 逐欄比對。
唔改寫交付件一個字；stub 只模擬富途運行時 API（fbasic.Sequence／fplot／ftool.iff／plot*／input_parameter）。"""
import json, re, sys, types

SRC = "v4_futu_ftnn_hk.py"
FIX = "a36_fixture.json"

class Vec:
    def __init__(self, v): self.v = list(v)
    @property
    def values(self): return self.v
    @property
    def size(self): return len(self.v)
    def apply(self, f): return Vec([f(x) for x in self.v])
    def ref(self, k): return Vec([None]*k + self.v[:len(self.v)-k] if k else self.v)
    def __sub__(self, o):
        ov = o.v if isinstance(o, Vec) else o
        return Vec([a-b for a, b in zip(self.v, ov)])
    def __len__(self): return len(self.v)
    def __iter__(self): return iter(self.v)
    def __getitem__(self, i): return self.v[i]
    def __repr__(self): return "Vec(%d)" % len(self.v)

PLOTS = []; OUTPUTS = {}; INPUTS = []

def _rec(kind):
    def f(*a, **k):
        PLOTS.append({"kind": kind, "args": a, "kwargs": k})
        return Vec([0]*1) if kind == "plot" else None
    return f

def _iff(cond, a, b):
    cv = cond.v if isinstance(cond, Vec) else cond
    av = a.v if isinstance(a, Vec) else [a]*len(cv)
    bv = b.v if isinstance(b, Vec) else [b]*len(cv)
    return Vec([av[i] if cv[i] else bv[i] for i in range(len(cv))])

def _input_parameter(title, default):
    INPUTS.append((title, default)); return default

def _output_parameter(**kw): OUTPUTS.update(kw)

class _Color:
    @staticmethod
    def rgb(r, g, b, a=255): return ("rgb", r, g, b, a)
    blue = ("named", "blue"); white = ("named", "white"); gray = ("named", "gray")
    red = ("named", "red"); green = ("named", "green")

class _Line:
    line = "line"; line_dashed = "line_dashed"; line_dotted = "line_dotted"
    histogram = "histogram"; histogram_line = "histogram_line"; circles = "circles"; cross = "cross"

class _Shape:
    labelup = "labelup"; labeldown = "labeldown"; arrowup = "arrowup"; arrowdown = "arrowdown"
    circle = "circle"; square = "square"; diamond = "diamond"; flag = "flag"
    triangleup = "triangleup"; triangledown = "triangledown"; cross = "cross"; xcross = "xcross"

def main():
    fx = json.load(open(FIX))
    bars = fx["input_bars_ts_o_h_l_c_v"]
    o = [b[1] for b in bars]; h = [b[2] for b in bars]; l = [b[3] for b in bars]; c = [b[4] for b in bars]

    ftool = types.ModuleType("ftool"); ftool.iff = _iff
    fta = types.ModuleType("fta"); fmath = types.ModuleType("fmath"); fdt = types.ModuleType("fdatetime")
    ns = {"__name__": "__main__", "__builtins__": __builtins__,
          "indicator": lambda *a, **k: None, "input_parameter": _input_parameter,
          "output_parameter": _output_parameter, "plot": _rec("plot"),
          "plot_text": _rec("plot_text"), "plot_icon": _rec("plot_icon"),
          "plot_fillcolor": _rec("plot_fillcolor"), "plot_candlestick": _rec("plot_candlestick"),
          "plot_hline": _rec("plot_hline"), "plot_stickline": _rec("plot_stickline"),
          "Color": _Color, "Line": _Line, "Shape": _Shape,
          "open": lambda: Vec(o), "high": lambda: Vec(h), "low": lambda: Vec(l), "close": lambda: Vec(c)}
    sys.modules["ftool"] = ftool; sys.modules["fta"] = fta
    sys.modules["fmath"] = fmath; sys.modules["fdatetime"] = fdt
    code = open(SRC, encoding="utf-8").read()
    exec(compile(code, SRC, "exec"), ns)

    R = ns["R"]; N = R["n"]
    print("exec OK；bars =", N, "；inputs =", len(INPUTS), "；plot calls =", len(PLOTS), "；outputs =", len(OUTPUTS))

    tol = 1e-9
    def close_enough(g, e):
        if isinstance(e, bool) or isinstance(g, bool): return g == e
        if isinstance(e, (int, float)) and isinstance(g, (int, float)):
            return abs(g - e) <= tol * max(1.0, abs(e))
        return g == e

    bad = []; tot = 0
    keymap = {"st": "st", "erSmooth": "erSmooth", "volRatio": "volRatio",
              "adaptiveFactor": "adFactor", "adaptiveConfirm": "adConfirm",
              "lockedBull": "locked", "qualityPct": "qPct", "qualityGrade": "qGrade", "s": "conv"}
    for cp in fx["expected_checkpoints"]:
        i = cp["index"]
        for ek, gk in keymap.items():
            tot += 1
            if not close_enough(R[gk][i], cp[ek]):
                bad.append(("checkpoint", i, ek, cp[ek], R[gk][i]))
    # latest 20 欄
    L = R["n"] - 1
    got_latest = {"direction": "LONG" if R["bull"][L] else "SHORT", "st": R["st"][L], "close": c[L],
                  "age": R["age"][L], "convictionPct": ns["_round_half_away"](R["conv"][L]*100.0),
                  "erSmooth": R["erSmooth"][L], "volRatio": R["volRatio"][L],
                  "adaptiveFactor": R["adFactor"][L], "adaptiveConfirm": R["adConfirm"][L],
                  "hasFlipped": R["hasFlip"][L], "flipQuality": R["flipQ"][L],
                  "distancePct": abs(c[L]-R["st"][L])/c[L]*100.0, "bullFlips": R["bullCt"][L],
                  "bearFlips": R["bearCt"][L], "flipUp": R["flipUp"][L], "flipDown": R["flipDown"][L],
                  "anyFlip": R["anyFlip"][L]}
    got_latest["erState"] = "TRENDING" if R["erSmooth"][L] > 0.65 else "MIXED" if R["erSmooth"][L] > 0.40 else "CHOPPY"
    got_latest["volState"] = "HIGH" if R["volRatio"][L] > 1.20 else "LOW" if R["volRatio"][L] < 0.80 else "NORMAL"
    got_latest["flipGrade"] = R["flipG"][L]
    zh = {"directionZh": {"LONG": "做多", "SHORT": "做空"}[got_latest["direction"]],
          "erStateZh": {"TRENDING": "順勢趨勢", "MIXED": "多空交戰", "CHOPPY": "震盪洗盤"}[got_latest["erState"]],
          "volStateZh": {"HIGH": "波動劇烈", "LOW": "波動壓縮", "NORMAL": "波動正常"}[got_latest["volState"]]}
    for k, exp in fx["expected_latest"].items():
        tot += 1
        g = zh[k] if k in zh else got_latest.get(k, "MISSING")
        if not close_enough(g, exp): bad.append(("latest", k, exp, g))
    # labels
    gl = []
    for i in range(N):
        if R["flipUp"][i]:
            gl.append({"barIndex": i, "direction": "LONG", "quality": R["qPct"][i], "grade": R["qGrade"][i],
                       "y": R["st"][i], "close": c[i], "yloc": "belowbar", "style": "label_up"})
        if R["flipDown"][i]:
            gl.append({"barIndex": i, "direction": "SHORT", "quality": R["qPct"][i], "grade": R["qGrade"][i],
                       "y": R["st"][i], "close": c[i], "yloc": "abovebar", "style": "label_down"})
    el = fx["expected_labels"]
    tot += len(el) * 7
    if len(gl) != len(el): bad.append(("labels", "count", len(el), len(gl)))
    for a, b in zip(gl, el):
        for k in ("barIndex", "direction", "quality", "grade", "y", "close", "yloc"):
            if not close_enough(a[k], b[k]): bad.append(("label", b["barIndex"], k, b[k], a[k]))
    # 繪圖層：主線序列 == st（暖機 nan）；標籤文字棒位
    main = [p for p in PLOTS if p["kind"] == "plot" and p["args"][0] == ns["W"]["line"]]
    if not main: bad.append(("plot", "main line missing", "", ""))
    else:
        mv = main[0]["args"][1]
        mv = mv.v if isinstance(mv, Vec) else mv
        for i in range(N):
            tot += 1
            exp = R["st"][i]
            got = mv[i]
            if exp is None:
                ok = (got != got) or (got is None)     # nan 或 None
            else:
                ok = close_enough(got, exp)
            if not ok: bad.append(("plot_st", i, exp, got))
    # 綁定對齊自檢必須全 0
    al = OUTPUTS.get("綁定對齊自檢")
    if al is None: bad.append(("output", "對齊自檢 missing", "", ""))
    else:
        av = al.v if isinstance(al, Vec) else al
        tot += 1
        if any(x != 0 for x in av): bad.append(("alignment", "nonzero", 0, sum(1 for x in av if x != 0)))
    # 合規掃描（AST 精確：只睇真碼，唔受註解／docstring 字樣影響）
    import ast
    tree = ast.parse(code)
    allowed = {"ftool", "fta", "fmath", "fdatetime", "fbasic", "fplot", "ffinance", "fquote", "findicator"}
    imports = []
    for nd in ast.walk(tree):
        if isinstance(nd, ast.Import):
            imports += [a.name.split(".")[0] for a in nd.names]
        elif isinstance(nd, ast.ImportFrom):
            imports.append((nd.module or "").split(".")[0])
    tot += 1
    badimp = [m for m in imports if m not in allowed]
    if badimp: bad.append(("compliance", "forbidden import", "", badimp))
    tot += 1
    if not imports or set(imports) - allowed: pass
    forbidden_names = {"math", "isnan", "isinf", "collections", "typing", "dataclasses"}
    used = set()
    for nd in ast.walk(tree):
        if isinstance(nd, ast.Name) and nd.id in forbidden_names: used.add(nd.id)
        if isinstance(nd, ast.Attribute) and isinstance(nd.value, ast.Name) and nd.value.id in forbidden_names:
            used.add(nd.value.id + "." + nd.attr)
    tot += 1
    if used: bad.append(("compliance", "forbidden name usage", "", sorted(used)))
    tot += 1
    calls = sorted({nd.func.id for nd in ast.walk(tree)
                    if isinstance(nd, ast.Call) and isinstance(nd.func, ast.Name)
                    and nd.func.id in {"floor", "ceil", "isnan", "sqrt", "pow"}})
    if calls: bad.append(("compliance", "manual-outside math calls", "", calls))
    tot += 1
    imports_ok = sorted(set(imports))
    print("imports:", imports_ok, "｜plot calls:", len(PLOTS), "｜output_parameter:", len(OUTPUTS))

    print("逐欄比對：total =", tot, "｜mismatch =", len(bad))
    for b in bad[:40]: print("  MISMATCH", b)
    print("RESULT:", "PASS (0 diff)" if not bad else "FAIL")
    print("labels:", [(x["barIndex"], x["direction"], x["quality"], x["grade"]) for x in gl])
    print("label text samples:", [p["args"][3].v[158] if isinstance(p["args"][3], Vec) else p["args"][3]
                                  for p in PLOTS if p["kind"] == "plot_text"][:1])
    return 0 if not bad else 1

sys.exit(main())
