"""Actual5615-target HTTP batch and replay, exclusively in a temporary store."""
from contextlib import closing
from http.server import ThreadingHTTPServer
from pathlib import Path
import sys
import tempfile
import threading

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT));sys.path.insert(0,str(PROJECT/'scripts'))
import requests
from pallet.mask_model_training_data import read,write,require,sha
from pallet.pallet_description_review import JointGallery,JointHandler
from pallet.pallet_description_batch import RELEASE
from pallet.pallet_description_simple import initial_description
from pallet.pallet_description_data import binding_guard
from check_mask_taxonomy_fast_ui import TestGuard


def main(release=RELEASE):
    key=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    with tempfile.TemporaryDirectory(prefix='batch-structure-all-',dir='/tmp/opencode') as scratch:
        g=JointGallery('existing',Path(scratch),key,guard=TestGuard(binding_guard()),presentation=release/'existing')
        class Quiet(JointHandler):
            def log_message(self,*args):pass
        server=ThreadingHTTPServer(('127.0.0.1',0),Quiet);server.gallery=g;server.daemon_threads=True
        worker=threading.Thread(target=server.serve_forever,daemon=True);worker.start()
        try:
            base=f'http://127.0.0.1:{server.server_port}';client=requests.Session();client.headers.update({'X-Review-Request':'1'})
            r=client.post(base+'/api/review/login',json=dict(key=key),timeout=30);r.raise_for_status()
            p=next(iter(g.proposals.values()));body=dict(binding=g.manifest_sha256,source_key=p['target_key'],source_binding=sha(p),batch_id='a'*32,
                items=[[k,0] for k in g.proposals],text='SYNTHETIC 全筛选序列统一结构描述',reviewer='SYNTHETIC all5615',scope=dict(class_filter='',state_filter='all'))
            single=read(release/'existing/manifest.json').get('reviewer_policy')
            if single:body.pop('reviewer')
            r=client.post(base+'/api/review/structure-batch/preview',json=body,timeout=90);r.raise_for_status();require(r.json()['count']==5615,'Incomplete all-target preview')
            body['preview_token']=r.json()['preview_token'];r=client.post(base+'/api/review/structure-batch/apply',json=body,timeout=120);r.raise_for_status()
            first=r.json();require(first['count']==5615 and not first['replayed'],'Incomplete all-target apply')
            request_bytes=int(r.request.headers['Content-Length']);require(request_bytes>65536,'Did not exercise larger protected body reader')
            r=client.post(base+'/api/review/structure-batch/apply',json=body,timeout=120);r.raise_for_status();require(r.json()['replayed'],'All-target retry not idempotent')
            values=g.editor.store.summary()
            for k,v in values.items():
                p=g.proposals[k];d=initial_description(p)
                require(v['revision']==1 and v['description']==dict(d,text=body['text']) and v['polygon']==p['polygon'] and v['class_id']==p['class_id'] and v['action']=='draft','All-target text-only invariant failed')
                if single:require(v['reviewer']=='复核人1','Missing reviewer did not default for full batch')
            with closing(g.editor.store.connect()) as db:
                count=db.execute('SELECT count(*) FROM events').fetchone()[0];receipts=db.execute('SELECT count(*) FROM structure_batches').fetchone()[0]
            require(count==5615 and receipts==1,'All-target retry duplicated events')
            attributes=read(release/'existing/manifest.json').get('batch_attributes_enabled',False)
            if attributes:
                attribute_body={k:v for k,v in body.items() if k not in ('text','preview_token')}
                attribute_body.update(batch_id='b'*32,items=[[k,1] for k in g.proposals],attributes=dict(legs=4,beams=2,material='金属'))
                r=client.post(base+'/api/review/structure-attributes-batch/preview',json=attribute_body,timeout=90);r.raise_for_status();attribute_body['preview_token']=r.json()['preview_token']
                r=client.post(base+'/api/review/structure-attributes-batch/apply',json=attribute_body,timeout=120);r.raise_for_status();require(r.json()['count']==5615 and r.json()['attributes_only'],'Incomplete attributes all-target apply')
                r=client.post(base+'/api/review/structure-attributes-batch/apply',json=attribute_body,timeout=120);r.raise_for_status();require(r.json()['replayed'],'All attributes replay failed')
                for k,v in g.editor.store.summary().items():
                    old=values[k]
                    require(v['revision']==2 and v['description']=={**old['description'],**attribute_body['attributes']} and v['action']==old['action'] and v['polygon']==old['polygon'] and v['class_id']==old['class_id'] and v['structure_batch']==old['structure_batch'] and v['reviewer']=='复核人1','Attributes changed unrelated content')
                with closing(g.editor.store.connect()) as db:
                    count=db.execute('SELECT count(*) FROM events').fetchone()[0];receipts=db.execute('SELECT count(*) FROM structure_batches').fetchone()[0]
                require(count==11230 and receipts==2,'Attributes replay duplicated all-target events')
            write(release/'all5615_verified.json',dict(state='all5615_actual_HTTP_batch_and_replay_passed',targets=5615,request_bytes=request_bytes,events=count,batch_receipts=receipts,text_batch_events=5615,
                text_batch_only_text_changed=True,attributes_batch_only_attributes_changed=bool(attributes),final_event_count=count,final_batch_receipts=receipts,
                attributes_applied_and_replayed=bool(attributes),all14_human_notes_preserved=True,geometry_not_completed=True,production_annotation_POSTs=0,default_reviewer_without_field=bool(single)))
            print(dict(state='all5615_actual_HTTP_batch_and_replay_passed',request_bytes=request_bytes))
        finally:server.shutdown();server.server_close();worker.join();g.close()


if __name__=='__main__':main()
