"""独立离线核验；Python 3.12 标准库，无网络或设备访问。"""
from pathlib import Path
import json
import struct
import datetime as dt
import math
import re
import uuid

def parse(d):
    shape=d['shape']; flat=d['flat']; chunks=d['range'].split(','); spans=[]
    if len(shape) not in (1,2) or len(chunks)!=len(shape) or math.prod(shape)!=len(flat): raise ValueError('数组形状错误')
    for part,size in zip(chunks,shape):
        if not re.fullmatch(r'[0-9]+(?::[0-9]+)?',part): raise ValueError('NumericRange语法错误')
        values=list(map(int,part.split(':'))); low=values[0]; high=values[-1]
        if len(values)==2 and low>=high: raise ValueError('NumericRange双端范围必须严格递增')
        if high>=size: raise ValueError('范围超出本地数组')
        spans.append(list(range(low,high+1)))
    coords=[[x] for x in spans[0]] if len(shape)==1 else [[r,c] for r in spans[0] for c in spans[1]]
    selected=[flat[p[0]] if len(shape)==1 else flat[p[0]*shape[1]+p[1]] for p in coords]
    return {'selected':selected,'shape':[len(x) for x in spans],'indices':coords}


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()
