"""Dedicated3418/3419, fast complete-content guard and immutable source namespace."""
import argparse
from http.server import ThreadingHTTPServer
import importlib.util
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_model_training_data import read,write,require
from pallet.cluster_targets import digest
from pallet.pallet_description_round5_data import ROOT,binding_guard,sources_current
from pallet.pallet_description_round5_release import REVIEW_SETS,RELEASE,bind_review_sets
from pallet.pallet_description_review import JointGallery,JointHandler


class FastHandler(JointHandler):
    def route(self):
        from urllib.parse import urlsplit
        if urlsplit(self.path).path=='/healthz' and self.command in ('GET','HEAD'):
            g=self.server.gallery
            return self.json(dict(status='ok',publication_version=g.publication_version,targets=g.count,editing_enabled=True,joint_description=True,
                right_button_pan=True,complete_then_next=True,description_policy=g.description_policy,structure_batch_enabled=g.structure_batch_enabled,
                structure_attributes_batch_enabled=g.structure_attributes_batch_enabled,reviewer_policy=g.reviewer_policy,
                navigation_performance_policy='parallel_complete_content_sha256_no_revision_cache_v1',source_guard=g.source_guard.stats()))
        return super().route()


def runtime_for(mode):
    bind_review_sets();s=REVIEW_SETS[mode];managed=s['managed'];root=s['root'];overlay=RELEASE/mode
    spec=importlib.util.spec_from_file_location('_round5_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"]}'
    runtime.__file__=str(PROJECT/f'scripts/serve_pallet_description_round5_{mode}.py')
    def configure():
        suites=ET.parse(ROOT/'regressions_final.xml').getroot().findall('testsuite')
        require(sum(int(v.attrib['tests']) for v in suites)>=211 and not sum(int(v.attrib.get(k,0)) for v in suites for k in ('errors','failures','skipped')),'Passing round5 regressions required')
        m=read(root/'manifest.json');seal=read(root/'verification.json');ui=read(overlay/'checks/ui_acceptance.json');extra=read(overlay/'round5_browser_verification.json')
        require(seal['state']=='passed_joint_description_source_K_and_no_old_image_reuse' and seal['manifest_sha256']==digest(root/'manifest.json'),'Source/strictK/dedup 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,'Full actual browser safety acceptance required')
        require(ui['task_manifest_sha256']==seal['manifest_sha256'] and ui['overlay_manifest_sha256']==digest(overlay/'manifest.json'),'Browser/task presentation differs')
        require(extra['state']=='passed_round5_actual_task_desktop_and390_atomic_batch_and_fast_navigation' and extra['task_manifest_sha256']==seal['manifest_sha256'],'New namespace fast-navigation verification required')
        for n,h in extra['implementation_sha256'].items():require(digest(PROJECT/n)==h,'Tested implementation changed')
        for n,h in ui['implementation_sha256'].items():require(digest(PROJECT/n)==h,'Tested base editor changed')
        for n,h in extra['adapted_test_sources'].items():require(digest(overlay/'adapted_test_code'/n)==h,'Actual safety test changed')
        require(extra['performance_sha256']==digest(ROOT/f'browser_performance/{mode}/navigation_benchmark.json'),'Navigation test evidence changed')
        require(digest(root/'proposals.jsonl')==m['proposals_sha256'] and sources_current(),'Source changed before publication')
        require(read(ROOT/'training_verification.json')['state']=='round5_actual_training_and_latest_source_replay_passed','Actual training replay required')
        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 task namespace')
        else:write(managed/'runtime.json',value)
    def healthy():
        import json
        from urllib.request import urlopen
        try:
            with urlopen(runtime.LOCAL+'/healthz',timeout=4) as r:h=json.load(r)
            return h['publication_version']==s['namespace'] and h['targets']==read(root/'manifest.json')['request_count'] and h['source_guard']['parallel_full_content']
        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=overlay)
        server=ThreadingHTTPServer(('127.0.0.1',s['port']),FastHandler);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()))
