"""New2041 model's dedicated endpoint; do not replace completed337/145 services."""
import argparse
import fcntl
from http.server import ThreadingHTTPServer
import json
import logging
import os
from pathlib import Path
import signal
import socket
import subprocess
import sys
import threading
import time
from urllib.request import urlopen

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT));sys.path.insert(0,str(PROJECT/'scripts'))
from pallet.mask_annotation_update_v2_review import Updated2041KeypointGallery
from pallet.mask_annotation_update_v2_requests import ROOT,NAMESPACE
from pallet.mask_model_review import ModelMaskHandler
from pallet.cluster_targets import digest
from serve_structure_review import Child,process_identity,read_json,write_json,timestamp

STATE=PROJECT/'outputs/pallet_mask_annotation_update_managed_v2';REVIEWS=PROJECT/'outputs/pallet_mask_model_reviews_v5'
CHECKS=PROJECT/'outputs/pallet_mask_annotation_update_checks_v2';PORT=3408;LOCAL='http://127.0.0.1:3408'
CLOUDFLARED=Path('/tmp/opencode/pallet_review_tunnel/cloudflared')


def configure():
    m=read_json(ROOT/'manifest.json');v=read_json(ROOT/'verification.json');ui=read_json(CHECKS/'ui_acceptance/ui_acceptance.json')
    if (v.get('state')!='passed_updated_M2_sources_new_images_classK_exports_not_accuracy' or v.get('manifest_sha256')!=digest(ROOT/'manifest.json')
            or ui.get('state')!='passed_actual_headless_Chromium_isolated_fullflow_not_real_Safari'
            or ui.get('manifest_sha256')!=digest(ROOT/'manifest.json') or ui.get('production_annotation_writes')!=0 or ui.get('page_errors')
            or len(ui.get('viewports',[]))!=2 or not all(x.get('initial_machine_proposals_still_exact_class_K') and x.get('human_added_point_save_and_reload')
                and x.get('add_delete_vertex') and x.get('stale_tab_409_preserves_local_draft') for x in ui['viewports'])):
        raise ValueError('Independent actual2041 model/source replay plus actual temporary-store browser acceptance required')
    value=dict(schema='completed145_new2041_remaining_review_runtime_v2',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=m['request_count'],class_standard_sha256=m['class_standard_sha256'],checkpoint_sha256=m['checkpoint_sha256'],
        machine_candidates_not_human_complete=True,global_config_modified=False)
    STATE.mkdir(mode=0o700,exist_ok=True);path=STATE/'runtime.json'
    if path.exists():
        if read_json(path)!=value:raise ValueError('Do not rebind existing worklist/runtime')
    else:
        with path.open('x') as f:json.dump(value,f)
        path.chmod(0o600)


def healthy():
    try:
        with urlopen(LOCAL+'/healthz',timeout=3) as r:v=json.load(r)
        return (v.get('publication_version')==NAMESPACE and v.get('targets')==read_json(ROOT/'manifest.json')['request_count']
            and v.get('editing_enabled') is True and v.get('human_keypoint_add_enabled') is True)
    except (OSError,ValueError):return False


def available():
    with socket.socket() as s:
        try:s.bind(('127.0.0.1',PORT));return True
        except OSError:return False


def running():
    v=read_json(STATE/'supervisor.json');pid=v.get('pid')
    return v if type(pid)is int and v.get('process_identity')==process_identity(pid) else None


def app():
    configure();key=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    gallery=Updated2041KeypointGallery(ROOT,REVIEWS,key);server=ThreadingHTTPServer(('127.0.0.1',PORT),ModelMaskHandler);server.gallery=gallery;server.daemon_threads=True
    try:server.serve_forever()
    finally:server.server_close()


def supervise():
    configure()
    if not available() or not CLOUDFLARED.is_file():raise ValueError('New dedicated port/tunnel unavailable; no old service stopped')
    with (STATE/'supervisor.lock').open('a') as lock:
        fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB);logging.basicConfig(level=logging.INFO)
        env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1',PYTHONDONTWRITEBYTECODE='1')
        child=Child('app',[sys.executable,str(Path(__file__).resolve()),'app'],STATE,env)
        tunnel=Child('tunnel',[str(CLOUDFLARED),'tunnel','--no-autoupdate','--url',LOCAL,'--protocol','http2'],STATE,env)
        stop=threading.Event();started=timestamp();identity=process_identity(os.getpid())
        for sig in (signal.SIGTERM,signal.SIGINT):signal.signal(sig,lambda *_:stop.set())
        def persist(status):
            v=dict(state=status,pid=os.getpid(),process_identity=identity,started_at=started,updated_at=timestamp(),app=child.status(),tunnel=tunnel.status(),
                public_url=tunnel.url,local_url=LOCAL,tunnel_connected=tunnel.connected,child_autorestart=True,boot_autostart_configured=False,temporary_url=True,
                task_directory=str(ROOT.relative_to(PROJECT)),manifest_sha256=digest(ROOT/'manifest.json'),source_namespace=NAMESPACE,editing_enabled=True,
                isolated_review_directory=str(REVIEWS.relative_to(PROJECT)),old_services_or_configs_modified=False)
            write_json(STATE/'supervisor.json',v);write_json(STATE/'public_access.json',v)
        persist('starting')
        try:
            while not stop.is_set():
                changed=child.ensure()
                if tunnel.process is not None or healthy():changed=tunnel.ensure() or changed
                changed=tunnel.read_tunnel_status() or changed
                if changed:persist('connected' if tunnel.connected and healthy() else 'reconnecting')
                stop.wait(1)
        finally:tunnel.stop();child.stop();tunnel.connected=False;persist('stopped')


def start(timeout):
    current=running()
    if current:print(json.dumps(dict(current,already_running=True)));return
    configure()
    if not available():raise ValueError('New port occupied; old services unchanged')
    with (STATE/'supervisor.log').open('ab') as log:p=subprocess.Popen([sys.executable,str(Path(__file__).resolve()),'run'],cwd=PROJECT,
        stdin=subprocess.DEVNULL,stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
    deadline=time.monotonic()+timeout
    while time.monotonic()<deadline:
        v=running()
        if v and v['pid']==p.pid and v.get('tunnel_connected') and healthy():print(json.dumps(v));return
        if p.poll() is not None:raise RuntimeError('New service failed; logs preserved')
        time.sleep(1)
    raise RuntimeError('New service still starting; old services unchanged')


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