"""Source versus actual output, using independent ZIP/lxml/POI/Pillow readers."""
from pathlib import Path
from zipfile import ZipFile
from io import BytesIO
import base64,hashlib,json,re,sys
from PIL import Image
from static_word_readers import source_features,output_features,norm

folder=Path(sys.argv[1]);destination=Path(sys.argv[2]);poi=Path(sys.argv[3]);rtf=Path(sys.argv[4])
assert not destination.exists(),'Never overwrite retained readings'
sha=lambda b:hashlib.sha256(b).hexdigest()
checks=[];rows=[]
def clean(text):return norm(re.sub(r'[\x00-\x08\x0e-\x1f]','',text.replace('\x07','\n').replace('\x0b','\n').replace('\x0c','\n')))
def check(file,control,expected,actual,passed=None):
    checks.append(dict(file=file,control=control,expected=expected,actual=actual,passed=expected==actual if passed is None else bool(passed)))
def picture_pixels(payload):
    with Image.open(BytesIO(payload)) as im:
        im=im.convert('RGBA');return (im.size,sha(im.tobytes()))
def zip_pictures(path,prefix):
    with ZipFile(path) as z:return [picture_pixels(z.read(n)) for n in z.namelist() if n.startswith(prefix) and not n.endswith('/')]
def doc_features(path):
    root=poi/path.name
    assert (root/'input.sha256').read_text()==sha(path.read_bytes())
    title,author=(root/'metadata.tsv').read_text().rstrip('\n').split('\t')
    return dict(body=[(root/'body.txt').read_text()],notes=[dict(kind=kind,text=(root/(kind+'s.txt')).read_text()) for kind in ['footnote','endnote']],
                sections={kind:[(root/(kind+'s.txt')).read_text()] for kind in ['header','footer']},metadata=dict(title=base64.b64decode(title).decode(),creator=base64.b64decode(author).decode()),tableCount=int((root/'table-count.txt').read_text()),comments=[dict(text=(root/'comments.txt').read_text())])

for meta in sorted(folder.glob('*.json')):
    info=json.loads(meta.read_text());file=info['file'];actual=folder/file;source=Path(info['source'])
    assert sha(source.read_bytes())==info['sourceSha256'] and sha(actual.read_bytes())==info['sha256']
    original=source_features(source)
    if info['to']=='odt':decoded=output_features(actual);pixels=zip_pictures(actual,'Pictures/')
    elif info['to']=='rtf':
        reconstructed=rtf/(actual.stem+'.docx');assert reconstructed.exists()
        decoded=source_features(reconstructed);pixels=zip_pictures(reconstructed,'word/media/')
    else:
        decoded=doc_features(actual);pixels=[picture_pixels(p.read_bytes()) for p in (poi/file).glob('picture-*.bin')]
    raw_body=clean(' '.join(decoded['body']));cursor=0
    for index,paragraph in enumerate(original['body']):
        position=raw_body.find(clean(paragraph),cursor);check(file,'source body paragraph '+str(index),clean(paragraph),raw_body,position>=cursor)
        if position>=cursor:cursor=position+len(clean(paragraph))
    for key in ['title','creator']:check(file,'original metadata '+key,norm(original['metadata'][key] or ''),norm(decoded['metadata'][key] or ''))
    for kind in ['header','footer']:
        text=clean(' '.join(decoded['sections'][kind]))
        for index,expected in enumerate(original['sections'][kind]):check(file,'source '+kind+' '+str(index),clean(expected),text,clean(expected) in text)
    for index,note in enumerate(original['notes']):
        text=clean(' '.join(n['text'] for n in decoded['notes'] if n['kind']==note['kind']))
        check(file,'original '+note['kind']+' body '+str(index),clean(note['text']),text,clean(note['text']) in text)
    if info['to']!='doc':
        ordered=decoded.get('referenceOrder',[dict(kind=n['kind'],text=n['text']) for n in decoded['notes']])
        check(file,'typed note reference order',original['referenceOrder'],ordered)
    check(file,'native table count',original['tableCount'],decoded['tableCount'])
    if info['to']=='doc':
        for index,comment in enumerate(original['comments']):
            actual_comments=clean(' '.join(c['text'] for c in decoded['comments']))
            check(file,'original comment body '+str(index),comment['text'],actual_comments,comment['text'] in actual_comments)
    else:
        want=sorted((c['text'],c['author'],c['rangeText']) for c in original['comments'])
        got=sorted((c['text'],c['author'],c['rangeText']) for c in decoded['comments'])
        check(file,'main-story comment text author and range',want,got)
    source_pixels=zip_pictures(source,'word/media/')
    check(file,'original picture RGBA pixels',source_pixels,pixels,all(p in pixels for p in source_pixels))
    rows.append(dict(file=file,fromFormat=info['from'],toFormat=info['to'],source=str(source),sourceSha256=info['sourceSha256'],bytes=actual.stat().st_size,sha256=info['sha256'],sourceFeatures=original,decodedFeatures=decoded,
                     reader='Apache POI5.4.1 binary DOC' if info['to']=='doc' else 'ZIP/lxml ODF' if info['to']=='odt' else 'Separate LibreOfficeDev26.8 RTF import to DOCX, then ZIP/lxml; same upstream family, not a competitive oracle'))
report=dict(readerVersion=2,retainedInitialReading='read-local1.json:792 observations/10 failed RTF note associations',complete=len(rows)==52,expectedFiles=52,files=len(rows),observations=len(checks),checks=checks,failures=[c for c in checks if not c['passed']],rows=rows,goalComplete=False,competitiveQuality='UNVERIFIED',limitations=[
    'Original source versus actual outputs; not app self round trips or CloudConvert parity.',
    'Ordered source body paragraph and note-body controls are finite retention checks, not a claim about every character or arbitrary document.',
    'Apache POI DOC note stories verify body content per type; note anchor identity/order is not inferred from its plain-text view.',
    'Apache POI DOC comments verify original comment text; author and range identity are not inferred from that plain-text view.',
    'RTF reading uses a separate desktop version of the same upstream family; native RTF syntax and rendering require additional views.',
    'Pillow verifies decoded original pictures; arbitrary fonts, layout, comments, fields and visual rendering are not established by structural passes.',
    'Wrappers, encodings, browser, frame, refusal/recovery and cancellation repetitions are not new original body corpora.',
    'Provider access was not retried after the retained quota refusal; comparative quality and quality-size curves are unverified.'])
destination.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
print(json.dumps(dict(complete=report['complete'],files=len(rows),observations=len(checks),failures=len(report['failures']))))
if not report['complete'] or report['failures']:sys.exit(1)
