"""Dedicated3412 service; original3406–3411 processes and tunnels untouched."""
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_data import REQUESTS, REVIEWS, MANAGED, NAMESPACE, sources_current
from pallet.mask_taxonomy_review import TaxonomyGallery, TaxonomyHandler
from pallet.mask_model_training_data import read, require, write
from pallet.cluster_targets import digest

spec=importlib.util.spec_from_file_location('_taxonomy_service_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=3412;runtime.LOCAL='http://127.0.0.1:3412'


def configure():
    m=read(REQUESTS/'manifest.json');seal=read(REQUESTS/'verification.json');ui=read(MANAGED/'checks_v2/ui_acceptance.json')
    require(seal['state']=='passed_independent_taxonomy_sources_K_quota_and_images' and seal['manifest_sha256']==digest(REQUESTS/'manifest.json'),'Independent exactK/new-image seal required')
    require(ui['state']=='passed_actual_taxonomy_Chromium_temp_stores' and ui['manifest_sha256']==seal['manifest_sha256'] and not ui['page_errors'] and ui['production_writes']==0,'Actual temporary-store browser acceptance required')
    require(ui['review_implementation_sha256']==digest(PROJECT/'pallet/mask_taxonomy_review.py'),'Browser-tested implementation changed')
    require(ui['ui_revision_sha256']==digest(REQUESTS/'ui_revision.json'),'Browser-tested UI presentation revision changed')
    suites=ET.parse(PROJECT/'outputs/pallet_mask_taxonomy_training_v1/regressions.xml').getroot().findall('testsuite')
    require(sum(int(s.attrib['tests']) for s in suites)>=235 and sum(int(s.attrib['failures'])+int(s.attrib['errors'])+int(s.attrib.get('skipped',0)) for s in suites)==0,'235 passing non-skipped regression tests required')
    require(sources_current(),'Source/protection changed; cannot start stale new tasks')
    from pallet.mask_taxonomy_keyboard_ui import active_configuration
    active_configuration()
    from pallet.mask_taxonomy_fast_ui import active_configuration as active_fast_configuration
    active_fast_configuration()
    from pallet.mask_taxonomy_pan_ui import validated_complete_configuration as active_complete_configuration,active_configuration as active_pan_configuration
    active_complete_configuration()
    active_pan_configuration()
    MANAGED.mkdir(mode=0o700,exist_ok=True)
    value=dict(schema=NAMESPACE,task_directory=str(REQUESTS.relative_to(PROJECT)),review_directory=str(REVIEWS.relative_to(PROJECT)),
        manifest_sha256=digest(REQUESTS/'manifest.json'),request_count=m['request_count'],port=3412,old_services_replaced=False)
    path=MANAGED/'runtime.json'
    if path.exists():require(read(path)==value,'Never rebind existing review 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()
    from pallet.mask_taxonomy_keyboard_ui import active_configuration,KeyboardGallery
    from pallet.mask_taxonomy_fast_ui import active_configuration as active_fast_configuration,FastGallery,FastHandler
    from pallet.mask_taxonomy_complete_ui import CompleteGallery,CompleteHandler
    from pallet.mask_taxonomy_pan_ui import validated_complete_configuration as active_complete_configuration,active_configuration as active_pan_configuration,PanGallery,PanHandler
    pan=active_pan_configuration();complete=active_complete_configuration();fast=active_fast_configuration();gallery_type=PanGallery if pan else CompleteGallery if complete else FastGallery if fast else KeyboardGallery if active_configuration() else TaxonomyGallery
    gallery=gallery_type(REQUESTS,REVIEWS,key);server=ThreadingHTTPServer(('127.0.0.1',3412),PanHandler if pan else CompleteHandler if complete else FastHandler if fast else TaxonomyHandler);server.gallery=gallery;server.daemon_threads=True
    try:server.serve_forever()
    finally:
        server.server_close()
        if fast: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())))
