"""Compare a current-office export with a backup downloaded from the hosted app."""
import argparse,json,sys
from pathlib import Path

def verify(source,target):
    a=json.loads(Path(source).read_text(encoding='utf-8-sig'));b=json.loads(Path(target).read_text(encoding='utf-8-sig'))
    errors=[]
    if a['config']!=b['config']:errors.append('Field/settings configuration differs.')
    for key in ['records','transferDeletedRecords']:
        if key not in a:continue
        x={r['id']:r for r in a[key]};y={r['id']:r for r in b.get(key,[])}
        if x.keys()!=y.keys():errors.append(f'{key}: row IDs differ.')
        for rid in x.keys()&y.keys():
            for field in ['kind','team','payload','revision','updatedAt','updatedBy']:
                if field in x[rid] and x[rid][field]!=y[rid].get(field):errors.append(f'{key}: {rid} differs in {field}.')
    if 'transferAudit' in a:
        from collections import Counter
        canon=lambda r:json.dumps({k:r.get(k) for k in ['at','who','action','before_value','after_value']},sort_keys=True)
        missing=Counter(map(canon,a['transferAudit']))-Counter(map(canon,b.get('transferAudit',[])))
        if missing:errors.append('Source audit history is incomplete in the hosted backup.')
    if errors:
        print('TRANSFER DOES NOT MATCH:');print('\n'.join(errors[:30]));return False
    print('TRANSFER VERIFIED: config and all source row IDs, details, weekly values and revisions match. Source audit history is included when supplied.')
    print('Run this before anyone starts editing the hosted copy.');return True
if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('office_export');p.add_argument('hosted_backup');a=p.parse_args()
    try:sys.exit(0 if verify(a.office_export,a.hosted_backup) else 1)
    except Exception as e:print('Verification failed:',e,file=sys.stderr);sys.exit(1)
