"""Isolated3410 face-class graph review; original access code and source preservation."""
import argparse
import importlib.util
import json
from pathlib import Path
import sys
from http.server import ThreadingHTTPServer

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT));sys.path.insert(0,str(PROJECT/'scripts'))
from pallet.mask_class_correction import ROOT,STATE as REVIEWS,NAMESPACE
from pallet.mask_class_correction_review import ClassGallery,ClassHandler
from pallet.mask_model_training_data import require,read
from pallet.cluster_targets import digest

spec=importlib.util.spec_from_file_location('_class_correction_supervisor',PROJECT/'scripts/serve_mask_annotation_update_v2_requests.py')
runtime=importlib.util.module_from_spec(spec);spec.loader.exec_module(runtime);runtime.__file__=str(Path(__file__).resolve())
STATE=PROJECT/'outputs/pallet_mask_class_correction_managed_v1';CHECKS=PROJECT/'outputs/pallet_mask_class_correction_checks_v1';PORT=3410;LOCAL='http://127.0.0.1:3410'
runtime.STATE=STATE;runtime.REVIEWS=REVIEWS;runtime.ROOT=ROOT;runtime.CHECKS=CHECKS;runtime.PORT=PORT;runtime.LOCAL=LOCAL;runtime.NAMESPACE=NAMESPACE


def configure():
    release=CHECKS/'interface_v5/release'
    seal=read(ROOT/'verification.json');ui=read(release/'ui/ui_acceptance.json')
    require(seal['state']=='passed2200_class_candidates_source_K_majority_not_semantic_accuracy' and seal['manifest_sha256']==digest(ROOT/'manifest.json'),'Independent source/K/majority verification required')
    require(ui['state']=='passed_actual_class_graph_browser_temp_only' and ui['manifest_sha256']==digest(ROOT/'manifest.json') and ui['production_writes']==0,'Actual isolated class review browser acceptance required')
    require(ui.get('review_implementation_sha256')==digest(PROJECT/'pallet/mask_class_correction_review.py') and not ui['page_errors'] and len(ui['viewports'])==2,'Latest class review implementation not accepted')
    require(ui.get('ui_extension_sha256')==digest(CHECKS/'ui_extension_v5/manifest.json') and all(v.get('specified_class_move') and v.get('confirmed_samples_sticky_and_filter_independent') and v.get('full_card_and_reference_selection_without_button_toggle') for v in ui['viewports']),'Class destination/examples/card interaction acceptance required')
    persistence=read(release/'persistence/acceptance.json')
    require(persistence['review_implementation_sha256']==ui['review_implementation_sha256'] and persistence['ui_extension_sha256']==ui['ui_extension_sha256'] and persistence['production_writes']==0 and not persistence['page_errors'] and len(persistence['viewports'])==2 and all(v['refresh_reload_new_tab_preserve_confirmation'] and v['unrelated_K12_split_preserves_four_classes'] and v['changed_Class1_only_invalidated'] for v in persistence['viewports']),'Actual confirmation persistence/scoped invalidation regression required')
    reuse=read(release/'old_class_reuse/acceptance.json');sync=read(release/'destination_sync/acceptance.json')
    for proof in (reuse,sync):require(proof['review_implementation_sha256']==ui['review_implementation_sha256'] and proof['ui_extension_sha256']==ui['ui_extension_sha256'] and proof['production_writes']==0 and not proof['page_errors'] and len(proof['viewports'])==2,'Latest reuse/sync implementation not accepted')
    require(all(v['no_majority_reuse'] and v['whole_group_not_only_checkboxes'] and v['manual_not_retain_provenance'] and v['unrelated_confirmations_preserved'] for v in reuse['viewports']),'Actual old-Class reuse interaction required')
    STATE.mkdir(mode=0o700,exist_ok=True);value=dict(manifest_sha256=digest(ROOT/'manifest.json'),root=str(ROOT.relative_to(PROJECT)),reviews=str(REVIEWS.relative_to(PROJECT)),namespace=NAMESPACE,port=PORT)
    path=STATE/'runtime.json'
    if path.exists():require(read(path)==value,'Do not rebind class correction service')
    else:path.write_text(json.dumps(value));path.chmod(0o600)
    from pallet.mask_class_note_integration_runtime import active_configuration
    active_configuration()


def app():
    configure();key=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    from pallet.mask_class_note_integration_runtime import active_configuration
    active=active_configuration()
    if active:
        from pallet.mask_class_note_integration import IntegratedGallery,IntegratedHandler
        gallery=IntegratedGallery(PROJECT/active['root'],PROJECT/active['reviews'],key);handler=IntegratedHandler
    else:gallery=ClassGallery(ROOT,REVIEWS,key);handler=ClassHandler
    server=ThreadingHTTPServer(('127.0.0.1',PORT),handler);server.gallery=gallery;server.daemon_threads=True
    try:server.serve_forever()
    finally:server.server_close()


def healthy():
    from urllib.request import urlopen
    try:
        with urlopen(LOCAL+'/healthz',timeout=3) as response:value=json.load(response)
        return value.get('service')==NAMESPACE and value.get('targets')==2200
    except (OSError,ValueError):return False


runtime.configure=configure;runtime.app=app;runtime.healthy=healthy

if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('command',choices=('app','run','start','status'));p.add_argument('--timeout',type=int,default=120);a=p.parse_args()
    if a.command=='app':app()
    elif a.command=='run':runtime.supervise()
    elif a.command=='start':runtime.start(a.timeout)
    else:print(json.dumps(dict(supervisor=runtime.running(),healthy=healthy())))
