"""Decode raw SWD records; format/coherence values do not prove physical testing."""
import argparse,json,struct
from pathlib import Path
FIELDS='magic version epoch windows active_windows last_cycles max_cycles last_us max_us last_gap_us max_gap_us fault core_hz limit_cycles limit_us flags'.split()
def decode(payload,epoch_before=None,epoch_after=None):
 if len(payload) not in (64,104):raise ValueError('record must be 64 bytes, or retained snapshot 104 bytes')
 d=dict(zip(FIELDS,struct.unpack('<16I',payload[:64])))
 if d['magic']!=0x544d3830 or d['version']!=1:raise ValueError('unsupported magic/version')
 if d['epoch']&1:raise ValueError('live timing epoch is odd')
 if (d['core_hz'],d['limit_cycles'],d['limit_us'])!=(128000000,3840,30):raise ValueError('unexpected candidate clock/limits')
 if d['fault']>4 or d['flags']&~3:raise ValueError('unknown status')
 if d['active_windows']>d['windows']:raise ValueError('active windows exceeds total')
 valid=d['fault']==0 and d['flags']==3 and d['windows']>0
 if valid and not(0<d['last_cycles']<=d['max_cycles']<=3840 and d['last_us']<=d['max_us']<=30 and d['max_gap_us']<=30):raise ValueError('validity conflicts with recorded limits')
 if d['fault'] and d['flags']&2:raise ValueError('fault snapshot cannot carry completed-window validity')
 out={'status':'DECODED_UNVERIFIED_RECORD','timing':d,'completed_window_within_supplied_limits':valid,'physical_validation':False,'actual_hardware_source_proven':False,'continuous_20kHz_qualified':False,'coherence_values_consistent':False}
 if len(payload)==104:
  if epoch_before is None or epoch_after is None:raise ValueError('retained snapshot requires bracketing capture epochs')
  if epoch_before!=epoch_after or epoch_before&1:raise ValueError('capture epoch changed or is odd')
  ia,ib,timer,armed,observed,sequence,calibrated=struct.unpack('<HHH2xIIIB3x',payload[64:88])
  dual,config,received,stream_epoch=struct.unpack('<4I',payload[88:])
  if ia>4095 or ib>4095 or calibrated>1 or stream_epoch&1:raise ValueError('invalid raw sample or stream epoch')
  out['coherence_values_consistent']=True;out['supplied_capture_epoch']=epoch_after
  out['stream']={'ia_raw':ia,'ib_raw':ib,'timer_count':timer,'armed_us':armed,'observed_us':observed,'sequence':sequence,'calibration_verified':bool(calibrated),'dual_state':dual,'config_state':config,'received':received,'epoch':stream_epoch}
 return out
if __name__=='__main__':
 ap=argparse.ArgumentParser();ap.add_argument('file',type=Path);ap.add_argument('--epoch-before',type=lambda x:int(x,0));ap.add_argument('--epoch-after',type=lambda x:int(x,0));ns=ap.parse_args()
 try:print(json.dumps(decode(ns.file.read_bytes(),ns.epoch_before,ns.epoch_after),indent=2))
 except ValueError as ex:ap.exit(2,str(ex)+'\n')
