"""Readonly public/local deployment acceptance and final no-source-write receipt."""
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing
import hashlib
import json
from pathlib import Path
import sys
import xml.etree.ElementTree as ET

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT));sys.path.insert(0,str(PROJECT/'scripts'))
from pallet.mask_class_note_corrections import ROOT,STATE,CHECKS,NAMESPACE
from pallet.mask_model_training_data import read,write,require,jsonl
from pallet.mask_template_refined import readonly
from pallet.mask_quality_recovery import fingerprint
from pallet.cluster_targets import digest
from review_http_pool import ReadOnlyHTTP
from audit_mask_class_note_corrections import audit


def check():
    require(not (CHECKS/'HANDOFF.json').exists(),'Preserve note correction final handoff')
    m=read(ROOT/'manifest.json');seal=read(ROOT/'verification.json');ui=read(CHECKS/'ui_v3/ui_acceptance.json');deps=read(ROOT/'private/dependencies.json')
    require(seal['state']=='passed_note_source_scope_and_editor_binding_not_correction_quality' and ui['state']=='passed_note_correction_actual_Chromium_temp_only','Source/UI acceptance missing')
    require(seal['manifest_sha256']==ui['manifest_sha256']==digest(ROOT/'manifest.json') and ui['review_implementation_sha256']==digest(PROJECT/'pallet/mask_class_note_corrections.py') and not ui['page_errors'] and ui['production_writes']==0,'Evidence implementation binding changed')
    require(len(ui['viewports'])==2 and all(v['actual_edge_additions_4_to12'] and v['actual_selected_vertex_delete_5_to4_and9_to8'] and v['stale_tab409'] and v['explicit_exclusion_preserves_source'] and v['occluded14_not_padded_or_merged'] for v in ui['viewports']),'Actual required UI actions missing')
    suites=ET.parse(CHECKS/'regressions.xml').getroot().findall('testsuite');tests=sum(int(s.attrib['tests']) for s in suites)
    require(tests>=189 and sum(int(s.attrib['errors'])+int(s.attrib['failures'])+int(s.attrib.get('skipped',0)) for s in suites)==0,'Regression failures/incomplete run')
    with closing(readonly(PROJECT/deps['class_graph_path'])) as db:
        row=db.execute("SELECT revision,payload FROM reviews WHERE target_key='class_graph'").fetchone();events=list(db.execute("SELECT payload FROM events WHERE target_key='class_graph' ORDER BY revision"))
    require(row[0]==421 and hashlib.sha256(row[1].encode()).hexdigest()==deps['class_graph_raw_sha256'] and [hashlib.sha256(raw.encode()).hexdigest() for raw, in events]==deps['old_class_events_sha256'],'Completed421 class/attribute history changed')
    for p,h in deps['human_source_fingerprints'].items():require(fingerprint(PROJECT/p)==h,'Original manual source changed')
    runtime=read(PROJECT/'outputs/pallet_mask_class_note_managed_v1/public_access.json');names=list(m['public_assets'])
    with ReadOnlyHTTP(runtime['public_url']) as client:
        health=client.get('/healthz').json();require(health['service']==NAMESPACE and health['targets']==90,'Wrong note editor public endpoint')
        require(client.get('/').content==(ROOT/'report_zh.html').read_bytes(),'Public note page bytes differ')
        def asset(name):
            data=client.get('/'+name).content;require(hashlib.sha256(data).hexdigest()==m['public_assets'][name],'Public note resource differs: '+name);return name
        with ThreadPoolExecutor(max_workers=4) as pool:checked=list(pool.map(asset,names))
        client.get('/api/review/targets/'+jsonl(ROOT/'tasks.jsonl')[0]['target_key'],expected=401)
        for path in ('/private/class_reviews.sqlite3','/private/dependencies.json','/private/class_graph_current.json','/manifest.json'):client.get(path,expected=404)
        secret=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip();client.login(secret,gallery=True)
        summary=client.get('/api/review/summary').json();completed=client.get('/api/review/export/completed.json').json()
        require(summary['source_current'] and not summary['reviews'] and not completed['records'],'Real note modifications unexpectedly present; do not overwrite or call them agent acceptance')
    current=audit();require(current['events']==0 and current['saved_targets']==0,'No real correction decisions should be written by agent')
    old_services=[]
    for port in (3406,3407,3408,3409,3410):
        with ReadOnlyHTTP(f'http://127.0.0.1:{port}') as client:
            h=client.get('/healthz').json();require(h['editing_enabled'],'Old review service stopped');old_services.append(dict(port=port,targets=h['targets']))
    value=dict(state='deployed_completed_class_note_correction_interface_not_automatic_annotation',public_url=runtime['public_url'],local_url=runtime['local_url'],
        source_class_graph_revision=421,source_all47_classes_and2200_targets_confirmed=True,issue_classes=m['issue_classes'],class_task_counts=m['class_task_counts'],targets=90,
        informational_Class15_not_in_error_queue=True,source_note_and_attribute_text_preserved=True,old421_raw_events_and_all_original_human_stores_unchanged=True,
        new_sidecar_review_store=str((STATE/'mask_reviews.sqlite3').relative_to(PROJECT)),actual_browser_widths=[1400,390],temporary_successful_saves=18,
        cpu_regressions=tests,public_resources_hash_checked=len(checked),production_annotation_or_exclusion_POST_attempts=0,production_correction_events=0,
        no_hidden_point_invention=True,no_K_resampling=True,correction_Class14_Class115_requires_actual_K4_K8=True,Class47_occlusion_not_automatically_merged=True,
        Class37_exclusion_not_source_deletion=True,existing_class_and_attribute_confirmations_not_reopened=True,no_training_no_GT_no_propagation=True,
        manifest_sha256=digest(ROOT/'manifest.json'),verification_sha256=digest(ROOT/'verification.json'),ui_acceptance_sha256=digest(CHECKS/'ui_v3/ui_acceptance.json'),
        regressions_sha256=digest(CHECKS/'regressions.xml'),review_implementation_sha256=digest(PROJECT/'pallet/mask_class_note_corrections.py'),
        old_services_preserved=old_services,original_access_code_retained_not_disclosed=True,temporary_Quick_Tunnel_URL=True,boot_autostart_configured=False,
        real_iPhone_Safari_tested=False,independent_correction_quality_accuracy=None,code_sha256=digest(__file__))
    write(CHECKS/'HANDOFF.json',value);print({k:value[k] for k in ('state','public_url','local_url','targets','issue_classes','cpu_regressions','production_correction_events')},flush=True)


if __name__=='__main__':check()
