"""Readonly final3412/tunnel check, full quota receipt and old-service preservation."""
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing
import hashlib
from pathlib import Path
import sys

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_model_training_data import read, write, require
from pallet.mask_taxonomy_data import ROOT,REQUESTS,REVIEWS,MANAGED,NAMESPACE,sources_current
from pallet.mask_template_refined import readonly
from review_http_pool import ReadOnlyHTTP


def check():
    require(not (MANAGED/'HANDOFF.json').exists(),'Preserve prior handoff evidence')
    require(sources_current(),'Sources changed before handoff')
    m=read(REQUESTS/'manifest.json');seal=read(REQUESTS/'verification.json');ui=read(MANAGED/'checks_v2/ui_acceptance.json')
    presentation=read(REQUESTS/'ui_revision.json')
    require(seal['manifest_sha256']==ui['manifest_sha256']==digest(REQUESTS/'manifest.json'),'Independent/UI receipt bindings differ')
    require(ui['production_writes']==0 and not ui['page_errors'],'Production test writes or browser errors')
    runtime=read(MANAGED/'public_access.json');secret=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    with ReadOnlyHTTP(runtime['public_url']) as client:
        health=client.get('/healthz').json();require(health['publication_version']==NAMESPACE and health['targets']==m['request_count'],'Wrong running new service')
        client.get('/api/review/catalog',expected=401)
        for path in ('/proposals.jsonl','/private/predictions.jsonl','/mask_reviews.sqlite3','/access_key.txt'):client.get(path,expected=404)
        names=list(m['public_assets'])+list(m['original_images'])
        def asset(name):
            raw=client.get('/'+name).content
            h=presentation['assets'][name]['sha256'] if name in presentation['assets'] else m['public_assets'].get(name) or m['original_images'][name]['sha256']
            require(hashlib.sha256(raw).hexdigest()==h,'Wrong published resource bytes: '+name)
            return name
        with ThreadPoolExecutor(max_workers=4) as pool:checked=list(pool.map(asset,names))
        client.login(secret,gallery=True);catalog=client.get('/api/review/catalog').json()
        require(len(catalog['quotas'])==41 and len(catalog['targets'])==m['request_count'],'Fine class quota counts differ live')
        pending=client.get('/api/review/unresolved').json();require(pending['not_counted_as_fine_class_quota'],'Uncertain candidates presented as confirmed fine class')
        first=catalog['targets'][0];detail=client.get('/api/review/targets/'+first['target_key']).json()
        require(detail['source_current'] and detail['proposal']['K']==len(detail['proposal']['polygon']),'Wrong live initialK/source')
    with closing(readonly(REVIEWS/'mask_reviews.sqlite3')) as db:
        actual_saves=db.execute('SELECT count(*) FROM events').fetchone()[0]
    require(actual_saves==0,'Synthetic acceptance must not write production review events')
    old=[]
    for port in (3406,3407,3408,3409,3410,3411):
        with ReadOnlyHTTP(f'http://127.0.0.1:{port}') as client:
            health=client.get('/healthz').json();require(health['editing_enabled'],'Old review service stopped')
            old.append(dict(port=port,publication_version=health.get('publication_version'),targets=health['targets']))
    quotas=read(ROOT/'release_quota_report.json');report=read(ROOT/'inference_complete.json')
    value=dict(state='new_taxonomy_training_inference_and_strict_new_image_review_published_with_explicit_gaps',
        public_url=runtime['public_url'],local_url=runtime['local_url'],temporary_Quick_Tunnel_URL=True,
        manifest_sha256=digest(REQUESTS/'manifest.json'),source_graph_revision=5,current_classes=43,train_and_quota_classes=41,
        class37_and47_unresolved_preserved=True,training_targets=2198,parent_classes=9,
        independent_holdout=read(REQUESTS/'summary.json')['independent_metrics'],
        inferred_remaining_targets=report['candidate_targets'],selected_new_distinct_images=m['request_count'],
        requested_new_images=4100,gap=4100-m['request_count'],per_class=quotas,
        unresolved_classification_targets=pending['count'],all_public_resources_verified=len(checked),
        production_synthetic_events=0,actual_Chromium_widths=[v['width'] for v in ui['viewports']],
        CPU_regressions=235,regressions_sha256=digest(ROOT/'regressions.xml'),
        real_iPhone_Safari_tested=False,old_services_preserved=old,
        no_formal_labels_human_histories_GT_or_robot_flags_overwritten=True,
        same_access_credential=True,code_sha256=digest(__file__))
    write(MANAGED/'HANDOFF.json',value)
    print({k:value[k] for k in ('state','public_url','local_url','inferred_remaining_targets','selected_new_distinct_images','gap')},flush=True)


if __name__=='__main__':check()
