"""独立离线核验；Python 3.12 标准库，无网络或设备访问。"""
from pathlib import Path
import json
import struct
import datetime as dt
import math
import re
import uuid

def parse(d):
    q=bytes.fromhex(d['request']); r=bytes.fromhex(d['response'])
    if len(q)<6 or q[0]!=16: raise ValueError('请求结构错误')
    n=int.from_bytes(q[3:5],'big')
    if not 1<=n<=123: raise ValueError('写入数量越界')
    if q[5]!=2*n or len(q)!=6+2*n: raise ValueError('写数据长度错误')
    if r!=q[:5]: raise ValueError('应答范围不符')
    return {'address':int.from_bytes(q[1:3],'big'),'quantity':n,'registers':[int.from_bytes(q[i:i+2],'big') for i in range(6,len(q),2)],'feedback_values':None}


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()
