"""Dedicated round4 supervisors on3416/3417; previous endpoints stay untouched."""
import argparse
from http.server import ThreadingHTTPServer
import importlib.util
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.mask_model_training_data import read,write,require
from pallet.cluster_targets import digest
from pallet.pallet_description_round4_data import ROOT,sources_current
from pallet.pallet_description_round4_guard import binding_guard
from pallet.pallet_description_round4_release import RELEASE,REVIEW_SETS,bind_review_sets
from pallet.pallet_description_review import JointGallery,JointHandler


def runtime_for(mode):
    bind_review_sets();s=REVIEW_SETS[mode];managed=s['managed'];root=s['root']
    spec=importlib.util.spec_from_file_location('_round4_supervisor_'+mode,PROJECT/'scripts/serve_mask_annotation_update_v2_requests.py')
    runtime=importlib.util.module_from_spec(spec);spec.loader.exec_module(runtime)
    runtime.STATE=managed;runtime.REVIEWS=s['reviews'];runtime.ROOT=root;runtime.NAMESPACE=s['namespace'];runtime.PORT=s['port'];runtime.LOCAL=f'http://127.0.0.1:{s["port"]}'
    # Child command must retain the mode argument; same supervisor executable otherwise.
    runtime.__file__=str(PROJECT/'scripts'/f'serve_pallet_description_round4_{mode}.py')
    def configure():
        import xml.etree.ElementTree as ET
        suites=ET.parse(ROOT/'round4_regressions_v3.xml').getroot().findall('testsuite')
        require(sum(int(v.attrib['tests']) for v in suites)>=179 and not sum(int(v.attrib.get(k,0)) for v in suites for k in ('failures','errors','skipped')),'Passing round4 regression contract required')
        m=read(root/'manifest.json');seal=read(root/'verification.json');overlay=RELEASE/mode;ui=read(overlay/'checks/ui_acceptance.json');extra=read(overlay/'round4_browser_verification.json')
        require(seal['manifest_sha256']==digest(root/'manifest.json') and seal['state']=='passed_joint_description_source_K_and_no_old_image_reuse','Task replay seal required')
        require(ui['state']=='passed_batch_attributes_real_Chromium' and not ui['page_errors'] and len(ui['viewports'])==2 and ui['production_annotation_POSTs']==0,'Real two-viewport batch acceptance required')
        require(ui['task_manifest_sha256']==seal['manifest_sha256'] and ui['overlay_manifest_sha256']==digest(overlay/'manifest.json'),'Browser/task/UI binding differs')
        require(extra['state']=='passed_round4_actual_task_desktop_and390_safety' and extra['production_annotation_POSTs']==0,'Round4 browser namespace verification required')
        require(extra['wrapper_sha256']==digest(PROJECT/'scripts/check_pallet_description_round4_ui.py'),'Browser wrapper changed')
        for name,h in extra['adapted_test_sources'].items():require(digest(overlay/'adapted_test_code'/name)==h,'Adapted safety test changed')
        for name,h in extra['implementation_sha256'].items():require(digest(PROJECT/name)==h,'Round4 guard/server implementation changed')
        for name,h in ui['implementation_sha256'].items():require(digest(PROJECT/name)==h,'Browser-tested implementation changed')
        require(digest(root/'proposals.jsonl')==m['proposals_sha256'] and sources_current(),'Sources/proposals changed; preserve old service')
        managed.mkdir(mode=0o700,exist_ok=True);value=dict(namespace=s['namespace'],port=s['port'],task_directory=str(root.relative_to(PROJECT)),review_directory=str(s['reviews'].relative_to(PROJECT)),manifest_sha256=seal['manifest_sha256'])
        if (managed/'runtime.json').exists():require(read(managed/'runtime.json')==value,'Do not rebind existing namespace')
        else:write(managed/'runtime.json',value)
    def healthy():
        import json
        from urllib.request import urlopen
        try:
            with urlopen(runtime.LOCAL+'/healthz',timeout=3) as response:v=json.load(response)
            return v['publication_version']==s['namespace'] and v['targets']==read(root/'manifest.json')['request_count'] and v['structure_attributes_batch_enabled']
        except (OSError,ValueError,KeyError):return False
    def app():
        configure();key=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
        g=JointGallery(mode,key=key,guard=binding_guard(),presentation=RELEASE/mode)
        server=ThreadingHTTPServer(('127.0.0.1',s['port']),JointHandler);server.gallery=g;server.daemon_threads=True
        try:server.serve_forever()
        finally:server.server_close();g.close()
    runtime.configure=configure;runtime.healthy=healthy;runtime.app=app
    return runtime


def main(mode):
    p=argparse.ArgumentParser();p.add_argument('command',choices=('app','run','start','status'));p.add_argument('--timeout',type=int,default=180);a=p.parse_args();runtime=runtime_for(mode)
    if a.command=='app':runtime.app()
    elif a.command=='run':runtime.supervise()
    elif a.command=='start':runtime.start(a.timeout)
    else:print(dict(supervisor=runtime.running(),healthy=runtime.healthy()))
