"""Local synthetic batch exercise. pypdf reads page counts; no remote API."""
import hashlib
import io
import json
import platform
from collections import Counter
from pathlib import Path
import pypdf
HERE=Path(__file__).resolve().parent

def main():
    pdf=(HERE.parent/'APDF-0883'/'synthetic-tables.pdf').read_bytes()
    malformed=b'SYNTHETIC INVALID PDF INPUT\n'
    rows=[{'item_id':f'SYN-I{i:02d}','fixture':'malformed' if i==4 else 'valid',
           'instruction':{3:'inject_transient_once',5:'cancel_before_start',6:'leave_queued'}.get(i,'run')}
          for i in range(1,9)]
    log=[]; outputs={}; states={}; attempts=Counter()
    def process(row, recovery=False):
        iid=row['item_id']; instruction=row['instruction']
        if states.get(iid)=='SUCCEEDED':
            log.append({'item_id':iid,'event':'REUSED_SUCCESS'});return
        if instruction=='cancel_before_start': states[iid]='CANCELLED';return
        if instruction=='leave_queued': states[iid]='QUEUED';return
        attempts[iid]+=1
        if instruction=='inject_transient_once' and not recovery:
            states[iid]='FAILED_RETRYABLE';log.append({'item_id':iid,'attempt':attempts[iid],'event':'INJECTED_TRANSIENT_FAILURE'});return
        data=malformed if row['fixture']=='malformed' else pdf
        try:
            pages=len(pypdf.PdfReader(io.BytesIO(data),strict=True).pages)
        except pypdf.errors.PdfReadError as e:
            states[iid]='FAILED_PERMANENT';log.append({'item_id':iid,'attempt':attempts[iid],'event':'PARSE_FAILURE','exception':type(e).__name__});return
        outputs[iid]={'item_id':iid,'page_count':pages,'source_sha256':hashlib.sha256(data).hexdigest(),'operation':'page-count-v1'}
        states[iid]='SUCCEEDED';log.append({'item_id':iid,'attempt':attempts[iid],'event':'PAGE_COUNT_SAVED'})
    for row in rows: process(row)
    initial=dict(Counter(states.values()))
    process(rows[2],recovery=True)
    for row in rows:
        if states[row['item_id']]=='SUCCEEDED': process(row,recovery=True)
    final=dict(Counter(states.values()))
    assert initial=={'SUCCEEDED':4,'FAILED_RETRYABLE':1,'FAILED_PERMANENT':1,'CANCELLED':1,'QUEUED':1}
    assert final=={'SUCCEEDED':5,'FAILED_PERMANENT':1,'CANCELLED':1,'QUEUED':1}
    assert len(outputs)==5 and all(x['page_count']==3 for x in outputs.values())
    report={'kind':'LOCAL_SYNTHETIC_BATCH_EXECUTION','python':platform.python_version(),'pypdf':pypdf.__version__,
            'network_calls':0,'http_api':'NOT_IMPLEMENTED','authentication':'NOT_TESTED','durability_across_restart':'NOT_TESTED',
            'initial_counts':initial,'final_counts':final,'states':states,'attempts':dict(attempts),
            'successful_output_count':len(outputs),'outputs':list(outputs.values()),'log':log,
            'limitations':['Page-count extraction only, not conversion/OCR or a throughput benchmark.','Transient failure, cancellation and queued item deliberately injected.']}
    request={'kind':'PROPOSED_INTERNAL_BATCH_CONTRACT','schema_version':'1','tenant':'SYN-T01','batch_id':'SYN-B01',
             'operation':'page-count-v1','atomicity':'INDEPENDENT_ITEMS','idempotency_key':'SYN-B01-v1','items':rows}
    (HERE/'batch-contract.json').write_text(json.dumps(request,indent=2)+'\n')
    (HERE/'batch-results.json').write_text(json.dumps(report,indent=2)+'\n')
    print(json.dumps({'initial':initial,'final':final,'outputs':len(outputs),'python':platform.python_version(),'pypdf':pypdf.__version__}))

if __name__=='__main__':main()
