"""Dedicated3409 correction service, reuse isolated supervised runtime machinery."""
import argparse
import importlib.util
import json
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_quality_override import ROOT,NAMESPACE
from pallet.mask_quality_override_review import CorrectionGallery,CorrectionHandler
from pallet.cluster_targets import digest

# A separate module instance keeps runtime globals separate from every old
# service. Its child process invokes THIS entrypoint and rebinds only new paths.
spec=importlib.util.spec_from_file_location('_quality_override_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.ROOT=ROOT;runtime.NAMESPACE=NAMESPACE
runtime.Updated2041KeypointGallery=CorrectionGallery;runtime.ModelMaskHandler=CorrectionHandler
STATE=PROJECT/'outputs/pallet_mask_quality_override_managed_v1';REVIEWS=PROJECT/'outputs/pallet_mask_model_reviews_v6'
CHECKS=PROJECT/'outputs/pallet_mask_quality_override_checks_v1';PORT=3409;LOCAL='http://127.0.0.1:3409'
runtime.STATE=STATE;runtime.REVIEWS=REVIEWS;runtime.CHECKS=CHECKS;runtime.PORT=PORT;runtime.LOCAL=LOCAL


def configure():
    read=runtime.read_json;m=read(ROOT/'manifest.json');v=read(ROOT/'verification.json');ui=read(CHECKS/'ui_acceptance/ui_acceptance.json')
    if (v.get('state')!='passed_unfiltered150_sources_exports_initialK_not_quality' or v.get('manifest_sha256')!=digest(ROOT/'manifest.json')
            or m.get('request_count')!=150 or m.get('quality_override_authorized') is not True or m.get('quality_certified') is not False
            or ui.get('state')!='passed_actual_headless_Chromium_isolated_fullflow_not_real_Safari' or ui.get('page_errors')
            or ui.get('manifest_sha256')!=digest(ROOT/'manifest.json') or ui.get('production_annotation_writes')!=0
            or len(ui.get('viewports',[]))!=2 or not all(x.get('human_added_point_save_and_reload') and x.get('stale_tab_409_preserves_local_draft') for x in ui['viewports'])):
        raise ValueError('Source/initial-K/export and actual temporary-store browser proof required, NOT a quality gate')
    value=dict(schema='authorized_quality_override_150_runtime_v1',task_directory=str(ROOT.relative_to(PROJECT)),review_directory=str(REVIEWS.relative_to(PROJECT)),
        manifest_sha256=digest(ROOT/'manifest.json'),source_namespace=NAMESPACE,request_count=150,quality_certified=False,template_placeholders_explicit=True,
        old_service_modified=False,count_unit='targets_not_necessarily_unique_images')
    STATE.mkdir(mode=0o700,exist_ok=True);path=STATE/'runtime.json'
    if path.exists():
        if read(path)!=value:raise ValueError('Do not rebind existing review history/runtime')
    else:
        with path.open('x') as stream:json.dump(value,stream)
        path.chmod(0o600)


runtime.configure=configure

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