"""Raw-byte before/after controls supplement independent semantic readers."""
from pathlib import Path
import hashlib,json,re,sys
from compare_native_odt import compare_native_odt
base=Path('benchmarks/research/word-editable1');phase=sys.argv[1]
assert phase in ['local2','production1']
destination=base/(sys.argv[2] if len(sys.argv)>2 else 'comparison-'+phase+'.json');assert not destination.exists()
sha=lambda b:hashlib.sha256(b).hexdigest()
def compare(before,after,expected,repairs):
    rows=[];unchanged=0;changed=0;containers=0
    for path in sorted(before.glob('*.json')):
        r=json.loads(path.read_text());name=r['file'];other=json.loads((after/(name+'.json')).read_text())
        assert r['sourceSha256']==other['sourceSha256'] and sha(Path(r['source']).read_bytes())==r['sourceSha256']
        a=(before/name).read_bytes();b=(after/name).read_bytes();assert sha(a)==r['sha256'] and sha(b)==other['sha256']
        fixed=False;container=None
        if a==b:unchanged+=1
        elif name.endswith('.odt'):
            container=compare_native_odt(before/name,after/name);containers+=1
        else:
            assert name.endswith('.rtf'),'Only known annotation placements may change'
            match=re.search(rb'\{\{\\\*\\atnid[\s\S]*?Original comment (?:letter|landscape)\}\}\}',a)
            assert match,'Changed file lacks the retained explicit fixture annotation'
            block=match.group(0);anchor=rb'{\*\atrfend 0}'
            assert a.count(block)==1 and a.count(anchor)==1
            wanted=a.replace(block,b'',1).replace(anchor,anchor+block,1)
            assert wanted==b and len(a)==len(b),'Bytes outside complete annotation relocation changed'
            fixed=True;changed+=1
        rows.append(dict(file=name,sourceSha256=r['sourceSha256'],beforeBytes=len(a),afterBytes=len(b),beforeSha256=sha(a),afterSha256=sha(b),wholeBytesUnchanged=a==b,annotationRelocationOnly=fixed,nativeOdtContainerComparison=container))
    assert len(rows)==expected and changed==repairs
    return dict(files=len(rows),wholeBytesUnchanged=unchanged,completeAnnotationRelocations=changed,nativeOdtContainersWithRecordedSessionFields=containers,allOtherContentBytesPreserved=True,rows=rows)
if phase=='local2':
    new=compare(base/'local1',base/'local2',52,10)
    native=compare(Path('benchmarks/research/word-static-editable1/live-baseline1'),base/'local2-native',18,4)
else:
    new=compare(base/'local2',base/'production1',52,0)
    native=compare(base/'local2-native',base/'production1-native',18,0)
report=dict(complete=True,goalComplete=False,phase=phase,newOperations=new,existingNativeOperations=native,competitiveQuality='UNVERIFIED',scope='Same actual input hashes, recorded native-default settings and whole output bytes. RTF annotation relocation preserves every other byte and the complete size. Native ODT ZIP timestamps, paired editing-session integers and linked annotation names are separately retained; all other uncompressed part bytes must match exactly. Native ODT files are not called whole-byte exact. This is a Tabmorph version/location or local/live comparison, not a provider quality-size curve. Browser/wrapper/encoding/recovery repetitions are not distinct original corpora.')
destination.write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(dict(complete=True,new=new['files'],newRepaired=new['completeAnnotationRelocations'],old=native['files'],oldRepaired=native['completeAnnotationRelocations'])))
