"""Separate managed model-review endpoint; old endpoints/configs never switch."""
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_model_review import ModelMaskGallery,ModelMaskHandler
from pallet.cluster_targets import digest
from serve_structure_review import Child,process_identity,read_json,write_json,timestamp

ROOT=PROJECT/'outputs/pallet_mask_model_requests_v1';STATE=PROJECT/'outputs/pallet_mask_model_managed_v1'
REVIEWS=PROJECT/'outputs/pallet_mask_model_reviews_v1';PORT=3405;LOCAL='http://127.0.0.1:3405'
CLOUDFLARED=Path('/tmp/opencode/pallet_review_tunnel/cloudflared')


def configure():
    m=read_json(ROOT/'manifest.json');v=read_json(ROOT/'verification.json')
    if v['state']!='passed_model_sources_exports_protection_not_accuracy' or v['manifest_sha256']!=digest(ROOT/'manifest.json'):
        raise ValueError('Verified model draft package required')
    ui=read_json(PROJECT/'outputs/pallet_mask_model_ui_acceptance_v3/ui_acceptance.json')
    if (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):
        raise ValueError('Actual isolated desktop/mobile browser acceptance required before serving new model drafts')
    value=dict(schema='model_native_review_runtime_v1',task_directory=str(ROOT.relative_to(PROJECT)),review_directory=str(REVIEWS.relative_to(PROJECT)),
        manifest_sha256=digest(ROOT/'manifest.json'),request_count=m['request_count'],target_per_class=100,model_checkpoint_sha256=m['checkpoint_sha256'],
        machine_candidates_not_human_complete=True,shares_old_production_store=False,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 a managed endpoint')
    else:
        with path.open('x') as stream:json.dump(value,stream)
        path.chmod(0o600)


def healthy():
    try:
        with urlopen(LOCAL+'/healthz',timeout=3) as r:v=json.load(r)
        return v.get('service')=='pallet_mask_model_preannotation_review' and v.get('targets')==read_json(ROOT/'manifest.json')['request_count']
    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()
    g=ModelMaskGallery(ROOT,REVIEWS,key);server=ThreadingHTTPServer(('127.0.0.1',PORT),ModelMaskHandler);server.gallery=g;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; old services intact')
    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,
                source_kind='actual_M2_checkpoint_machine_prelabels',task_directory=str(ROOT.relative_to(PROJECT)),manifest_sha256=digest(ROOT/'manifest.json'),
                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('Dedicated port occupied; no old service will restart')
    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; keep its own log')
        time.sleep(1)
    raise RuntimeError('New service still starting; no old endpoint changed')


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