"""独立离线核验；Python 3.12 标准库，无网络或设备访问。"""
from pathlib import Path
import json
import struct
import datetime as dt
import math
import re
import uuid

def parse(d):
    b=bytes.fromhex(d['hex'])
    if not b: raise ValueError('空NodeId')
    widths={0:2,1:4,2:7}
    if b[0] not in widths: raise ValueError('仅支持Numeric三种编码')
    if len(b)!=widths[b[0]]: raise ValueError('NodeId编码长度错误')
    if b[0]==0: name,ns,ident='TwoByte',0,b[1]
    elif b[0]==1: name,ns,ident='FourByte',b[1],int.from_bytes(b[2:4],'little')
    else: name,ns,ident='Numeric',int.from_bytes(b[1:3],'little'),int.from_bytes(b[3:7],'little')
    return {'encoding':name,'namespace':ns,'identifier':ident}


def main():
    root = Path(__file__).resolve().parent
    fixture = json.loads((root / "fixture.json").read_text(encoding="utf-8"))
    rows = []
    for item in fixture["cases"]:
        try:
            result = parse(item["input"])
        except ValueError as exc:
            assert "expected_error" in item, (item["case_id"], str(exc))
            assert str(exc) == item["expected_error"], (item["case_id"], str(exc))
            rows.append({"case_id": item["case_id"], "kind": item["kind"], "rejected": str(exc)})
        else:
            assert "expected_error" not in item, item["case_id"]
            assert result == item["expected"], (item["case_id"], result, item["expected"])
            rows.append({"case_id": item["case_id"], "kind": item["kind"], "result": result})
    report = {"fixture": fixture["topic"], "cases": rows, "assertions_passed": len(rows), "scope": "合成输入离线演算；未接真实设备"}
    (root / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({"assertions_passed": len(rows), "all_passed": True}, ensure_ascii=True))

if __name__ == "__main__":
    main()
