"""Replay supplied compiled measurement mappings; does not authenticate origin."""
import hashlib,json,re,sys

def require(value,message):
    if not value:raise ValueError(message)

def mapping(program):
    require(isinstance(program,str) and program.startswith('OPENQASM 3.0;'),'Captured IQM OpenQASM text required')
    declarations=re.findall(r'\bbit\s*\[\s*(\d+)\s*\]\s+b\s*;',program)
    require(len(declarations)==1 and declarations[0] in ['1','2'],'Single one- or two-bit register required')
    width=int(declarations[0]); result={}
    for statement in [part.strip() for part in program.split(';') if 'measure' in part]:
        match=re.search(r'\bb\s*\[\s*(\d+)\s*\]\s*=\s*measure\s*\$(\d+)\s*$',statement)
        require(match is not None,'Unsupported measurement statement')
        bit,physical=map(int,match.groups())
        require(bit not in result,'Classical bit measured twice')
        result[bit]=physical
    require(set(result)==set(range(width)) and len(set(result.values()))==width,'Complete distinct physical mapping required')
    return [result[index] for index in range(width)]

def audit(data):
    require(data.get('schema')=='qb.public-captured-iqm-mapping/v1' and data.get('backend')=='iqm-garnet','Unsupported mapping schema/provider')
    expected={'initial-00','initial-01','initial-10','initial-11','initial-monomer','initial-dimer','cal-0','cal-1','fresh-monomer'}
    rows=data['captures']; require(len(rows)==9 and {row['circuit'] for row in rows}==expected,'Exact nine distinct capture rows required')
    mappings={}
    for row in rows:
        require(hashlib.sha256(row['compiled_program'].encode()).hexdigest()==row['compiled_program_sha256'],'Compiled source hash mismatch')
        observed=mapping(row['compiled_program']); declared=row['physical_qubits_by_classical_bit']
        require(isinstance(declared,list) and all(type(q) is int and q>=0 for q in declared) and observed==declared,'Reported physical mapping differs')
        width=1 if row['circuit'] in {'initial-monomer','cal-0','cal-1','fresh-monomer'} else 2
        require(len(observed)==width,'Circuit register width differs')
        mappings[row['circuit']]=observed
    one=[mappings[key] for key in ['cal-0','cal-1','fresh-monomer']]
    probes=[mappings['initial-'+key] for key in ['00','01','10','11']]
    calculated={
        'one_qubit_calibration_and_fresh_monomer_same_physical_mapping':all(row==one[0] for row in one),
        'four_two_qubit_basis_rows_same_physical_mapping':all(row==probes[0] for row in probes),
        'all_two_qubit_basis_rows_match_dimer_mapping':all(row==mappings['initial-dimer'] for row in probes)}
    for key,value in calculated.items():require(data['checks'].get(key) is value,'Reported mapping claim differs')
    for key in ['physical_calibration_epoch_verified','stationary_channel_verified','authenticated_provider_execution_independently_verified']:
        require(data['checks'].get(key) is False,'Unsupported channel/authentication claim')
    return {'mapping_replay_passed':True,'physical_qubits_by_classical_bit':mappings,'checks':data['checks'],
            'provider_authentication_verified':False,'calibration_transfer_verified':False}

if __name__=='__main__':
    with open(sys.argv[1]) as file:data=json.load(file)
    print(json.dumps(audit(data),indent=2))
