"""Supervisor adapter shared by independent3414/3415, no existing process reloads."""
import argparse
import importlib.util
import json
from http.server import ThreadingHTTPServer
from pathlib import Path
import sys
import xml.etree.ElementTree as ET

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.mask_model_training_data import read,write,require
from pallet.cluster_targets import digest
from pallet.pallet_description_data import ROOT,sources_current
from pallet.pallet_description_review import SETS,JointGallery,JointHandler


def main(mode,script):
    s=SETS[mode];managed=s['managed'];root=s['root']
    spec=importlib.util.spec_from_file_location('_joint_description_supervisor_'+mode,PROJECT/'scripts/serve_mask_annotation_update_v2_requests.py')
    runtime=importlib.util.module_from_spec(spec);spec.loader.exec_module(runtime);runtime.__file__=str(script)
    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"]}'
    def configure():
        m=read(root/'manifest.json');seal=read(root/'verification.json');ui=read(managed/'checks/ui_acceptance.json')
        require(seal['state']=='passed_joint_description_source_K_and_no_old_image_reuse' and seal['manifest_sha256']==digest(root/'manifest.json'),'Independent joint-task seal required')
        require(ui['state']=='passed_actual_joint_description_temp_Chromium' and ui['manifest_sha256']==seal['manifest_sha256'] and ui['production_annotation_POSTs']==0
            and not ui['page_errors'] and len(ui['viewports'])==2,'Real desktop/narrow joint UI acceptance required')
        require(all(digest(PROJECT/name)==h for name,h in ui['implementation_sha256'].items()),'Browser-tested implementation changed')
        require(sources_current(),'Source changed; new version required')
        suites=ET.parse(ROOT/'regressions_330.xml').getroot().findall('testsuite');require(sum(int(v.attrib['tests']) for v in suites)>=330 and not sum(int(v.attrib['failures'])+int(v.attrib['errors'])+int(v.attrib.get('skipped',0)) for v in suites),'Passing frozen joint regressions required')
        managed.mkdir(mode=0o700,exist_ok=True);value=dict(namespace=s['namespace'],port=s['port'],manifest_sha256=digest(root/'manifest.json'),task_directory=str(root.relative_to(PROJECT)),review_directory=str(s['reviews'].relative_to(PROJECT)))
        if (managed/'runtime.json').exists():require(read(managed/'runtime.json')==value,'No runtime rebinding')
        else:write(managed/'runtime.json',value)
    def healthy():
        from urllib.request import urlopen
        try:
            with urlopen(runtime.LOCAL+'/healthz',timeout=3) as response:h=json.load(response)
            return h.get('publication_version')==s['namespace'] and h.get('targets')==read(root/'manifest.json')['request_count']
        except (OSError,ValueError):return False
    def app():
        configure();key=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip();g=JointGallery(mode,key=key)
        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
    p=argparse.ArgumentParser();p.add_argument('command',choices=['app','run','start','status']);p.add_argument('--timeout',type=int,default=150);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())))
