import json, hashlib
from pathlib import Path
p=Path(__file__).parent
b=json.loads((p/'result-B.json').read_text()); c=json.loads((p/'result-C.json').read_text())
bp=Path('/private/var/folders/21/wq30qp_s6m5f1fnbzq3vq5b80000gn/T/cdx-payment-template-B-vKnK5L')
bodies_b=json.loads((bp/'private-bodies.json').read_text()); bodies_b.update(json.loads((bp/'extra-private-bodies.json').read_text()))
bodies_c=json.loads(Path('/private/tmp/cdx-template-bodies-C.json').read_text()); bodies_c.update(json.loads(Path('/private/tmp/cdx-template-extra-bodies-C.json').read_text()))
def norm(body,report):
    body=json.loads(json.dumps(body)); trace=body.pop('trace_id')
    assert isinstance(trace,str) and len(trace)==13 and all(x in '0123456789abcdef' for x in trace)
    ids={x['template_id']:i+1 for i,x in enumerate(report['owned'])}
    def walk(x):
        if isinstance(x,list): return [walk(v) for v in x]
        if isinstance(x,dict):
            if 'template_id' in x:
                assert type(x['template_id']) is int and x['template_id'] in ids
                x['template_id']=ids[x['template_id']]
                for field in ('create_time','update_time'):
                    if field in x:
                        value=x[field]
                        assert isinstance(value,str) and len(value)==19
                        # Each main read already compared this timestamp against its own original table.
                        from datetime import datetime
                        assert datetime.strptime(value,'%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')==value
                        x[field]='SOURCE_VERIFIED_SECOND_TIME'
            return {k:walk(v) for k,v in x.items()}
        return x
    return walk(body)
assert set(bodies_b)==set(bodies_c) and len(bodies_b)==50
results=[]
for key in bodies_b:
    nb,nc=norm(bodies_b[key],b),norm(bodies_c[key],c)
    assert nb==nc,key
    digest=hashlib.sha256(json.dumps(nb,ensure_ascii=False,sort_keys=True,separators=(',',':')).encode()).hexdigest()
    results.append({'scenario':key,'complete_wire_equal_with_source_owned_id_time_mapping':True,'canonical_wire_sha256':digest})
out={'passed':True,'scenario_pairs':len(results),'mapped_fields':['only verified owned row template_id preserving integer type','only valid original-source-verified row create_time/update_time preserving string type','validated top trace removed'],'results':results}
(p/'wire-comparison.json').write_text(json.dumps(out,ensure_ascii=False,indent=2)+'\n')
print('PASS: 50 full wire pairs; exact owned ID/time mapping only, all other values/types/array order preserved')
