"""Actual current public editor resources and reads; no annotation POST allowed."""
from pathlib import Path
import json
import sys
import time
from urllib.request import urlopen

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT));sys.path.insert(0,str(PROJECT/'scripts'))
from pallet.cluster_targets import digest
from pallet.mask_class_keypoint_review import EXTENSION,EDIT_NOTICE
from pallet.pose_review_geometry import canonical
from scripts.review_http_pool import ReadOnlyHTTP
from scripts.verify_mask_class_keypoint_edit_extension import preservation


def main():
    destination=EXTENSION/'public_acceptance.json'
    if destination.exists():raise ValueError('Do not overwrite public acceptance evidence')
    state=json.loads((PROJECT/'outputs/pallet_mask_class_keypoint_managed_v1/public_access.json').read_text());local=state['local_url'];base=state['public_url']
    deadline=time.monotonic()+100
    while True:
        try:
            with urlopen(local+'/healthz',timeout=4) as r:health=json.load(r)
            if health.get('human_keypoint_add_enabled') is True:break
        except (OSError,ValueError):pass
        if time.monotonic()>deadline:raise TimeoutError('Dedicated editor did not enable add points; no other service modified')
        time.sleep(1)
    manifest=json.loads((EXTENSION/'editor_extension_manifest.json').read_text());root=PROJECT/'outputs/pallet_mask_model_requests_v3'
    proposals=[json.loads(s) for s in (root/'proposals.jsonl').read_text().splitlines()];checked=[]
    with ReadOnlyHTTP(base) as client:
        health=client.get('/healthz').json();assert health['human_keypoint_add_enabled'] and health['targets']==337 and health['editing_enabled']
        page=client.get('/').text;assert EDIT_NOTICE in page and '点数固定，不增删点' not in page
        assert '/review-ui/editor.js?v=class-keypoint-human-edit-v1' in page
        resources=[('/review-ui/editor.js?v=class-keypoint-human-edit-v1','editor.js'),('/review-ui/human-edit-font.otf','report-font.otf')]
        for route,name in resources:
            response=client.get(route);data=response.content
            import hashlib
            assert hashlib.sha256(data).hexdigest()==manifest['assets'][name]
            checked.append(dict(route=route,sha256=hashlib.sha256(data).hexdigest()))
        js=client.get('/review-ui/editor.js?v=class-keypoint-human-edit-v1').text
        assert 'polygon.splice(edge+1,0,point)' in js and 'mask-class-keypoints-v3:' in js
        assert 'if(detail.class_keypoint_constraint)' not in js
        client.get('/api/review/targets/'+proposals[0]['target_key'],expected=401)
        access=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip();client.login(access,gallery=True)
        sample=[]
        for cls in sorted({p['class_id'] for p in proposals}):
            p=next(p for p in proposals if p['class_id']==cls);key=p['target_key'];detail=client.get('/api/review/targets/'+key).json()
            assert detail['human_keypoint_count_editing_allowed'] is True
            assert len(detail['proposal_polygon'])==p['class_keypoint_constraint']['standard_count']
            sample.append(dict(class_id=cls,target_key=key,initial_standard_count=len(detail['proposal_polygon']),existing_real_revision=(detail.get('review') or {}).get('revision',0)))
            if detail['review']:
                export=client.get('/api/review/export/'+key+'/labelme.json').json();count=len(detail['review']['polygon'])
                assert export['num_keypoints']==count and len([s for s in export['shapes'] if s['shape_type']=='point'])==count
                assert export['keypoints_xy']==detail['review']['polygon']
                assert export['initial_standard_keypoint_count']==p['class_keypoint_constraint']['standard_count']
        kept=preservation()
        result=dict(state='passed_same_public_URL_local_port_add_point_editor_resources_and_authenticated_reads',
            public_url=base,local_url=local,health=health,resources=checked,authenticated_class_reads=sample,
            editor_extension_manifest_sha256=digest(EXTENSION/'editor_extension_manifest.json'),
            same_frozen_machine_proposal_ids_and_local_draft_keys=True,initial337_standard_counts_unchanged=True,
            original_human_history_preserved=kept,actual_annotation_POST_attempts=0,production_annotation_writes_by_agent=0,
            temporary_store_success_flow_verified_separately=True,real_Safari_tested=False,transport_retries=client.retries,code_sha256=digest(__file__))
        with destination.open('xb') as stream:stream.write(canonical(result)+b'\n')
    print(json.dumps(dict(state=result['state'],public_url=base,local_url=local,history=kept,production_annotation_writes=0)),flush=True)


if __name__=='__main__':main()
