"""Independent3413 endpoint; all3406–3412 services and their histories stay intact."""
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));sys.path.insert(0,str(PROJECT/'scripts'))
from pallet.mask_taxonomy_cycle2_data import ROOT,REQUESTS,REVIEWS,MANAGED,NAMESPACE,sources_current
from pallet.mask_taxonomy_cycle2_review import CycleGallery,CycleHandler,IMPLEMENTATIONS
from pallet.mask_model_training_data import read,write,require
from pallet.cluster_targets import digest

spec=importlib.util.spec_from_file_location('_taxonomy_cycle2_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())
runtime.STATE=MANAGED;runtime.REVIEWS=REVIEWS;runtime.ROOT=REQUESTS;runtime.NAMESPACE=NAMESPACE;runtime.PORT=3413;runtime.LOCAL='http://127.0.0.1:3413'


def configure():
    m=read(REQUESTS/'manifest.json');seal=read(REQUESTS/'verification.json');ui=read(MANAGED/'checks/ui_acceptance.json')
    require(seal['state']=='passed_cycle2_actual_training_sources_new_images_exactK' and seal['manifest_sha256']==digest(REQUESTS/'manifest.json'),'Independent actual model/new-image/K seal required')
    require(ui['state']=='passed_cycle2_real_Chromium_temp_only' and ui['manifest_sha256']==seal['manifest_sha256'] and ui['production_annotation_POSTs']==0
        and not ui['page_errors'] and len(ui['viewports'])==2 and all(v['complete_next_and_A_no_save'] and v['right_pan'] and v['K_and409'] and v['source_change_blocked'] for v in ui['viewports']),'Real desktop/narrow temporary-store acceptance required')
    require(set(ui['implementation_sha256'])==set(IMPLEMENTATIONS) and all(digest(PROJECT/name)==h for name,h in ui['implementation_sha256'].items()),'Browser-tested implementation changed')
    suites=ET.parse(ROOT/'regressions.xml').getroot().findall('testsuite')
    require(sum(int(s.attrib['tests']) for s in suites)>=301 and not sum(int(s.attrib['failures'])+int(s.attrib['errors'])+int(s.attrib.get('skipped',0)) for s in suites),'301 passing regressions required')
    require(sources_current(),'Source changes require a new training/task version')
    MANAGED.mkdir(mode=0o700,exist_ok=True);value=dict(schema=NAMESPACE,manifest_sha256=digest(REQUESTS/'manifest.json'),request_count=m['request_count'],
        port=3413,task_directory=str(REQUESTS.relative_to(PROJECT)),review_directory=str(REVIEWS.relative_to(PROJECT)),old_services_modified=False)
    path=MANAGED/'runtime.json'
    if path.exists():require(read(path)==value,'Never rebind second-cycle runtime')
    else:write(path,value)


def healthy():
    from urllib.request import urlopen
    try:
        with urlopen(runtime.LOCAL+'/healthz',timeout=3) as response:v=json.load(response)
        return v.get('publication_version')==NAMESPACE and v.get('targets')==read(REQUESTS/'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()
    gallery=CycleGallery(REQUESTS,REVIEWS,key);server=ThreadingHTTPServer(('127.0.0.1',3413),CycleHandler);server.gallery=gallery;server.daemon_threads=True
    try:server.serve_forever()
    finally:server.server_close();gallery.close()


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