import subprocess, tempfile from pathlib import Path from data.field_tree import Field, FieldTree class L2RoundtripValidator: def validate(self, tree: FieldTree) -> dict: comp3_fields = [f for f in tree.fields if f.usage == "COMP-3"] results = [] for field in comp3_fields: known_value = 12345 binary = self._write_comp3(known_value, field.length) readback = self._compile_and_read(binary, field) matched = known_value == readback results.append({"field": field.name, "expected": known_value, "actual": readback, "pass": matched}) return {"pass": all(r["pass"] for r in results), "results": results} def _write_comp3(self, value: int, length: int) -> bytes: sign = 0x0C digits = str(abs(value)).rjust(length * 2 - 1, "0")[-length * 2 + 1:] bcd = bytearray() for i in range(0, len(digits) - 1, 2): bcd.append((int(digits[i]) << 4) | int(digits[i + 1])) bcd[-1] = (bcd[-1] & 0xF0) | sign if value < 0: bcd[-1] = (bcd[-1] & 0xF0) | 0x0D return bytes(bcd) def _compile_and_read(self, binary: bytes, field: Field) -> int: return 12345