"""Class-standard initial drafts with human-addable keypoints; old sources preserved."""
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_class_keypoint_review import ClassKeypointGallery
from pallet.mask_model_review import ModelMaskHandler
from pallet.mask_class_keypoint_review import EXTENSION
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_v3';STATE=PROJECT/'outputs/pallet_mask_class_keypoint_managed_v1'
REVIEWS=PROJECT/'outputs/pallet_mask_model_reviews_v3';PORT=3406;LOCAL='http://127.0.0.1:3406'
CLOUDFLARED=Path('/tmp/opencode/pallet_review_tunnel/cloudflared')


def configure():
    m=read_json(ROOT/'manifest.json');v=read_json(ROOT/'verification.json')
    ui_path=PROJECT/'outputs/pallet_mask_class_keypoint_ui_v2/ui_acceptance.json';ui=read_json(ui_path)
    if (v.get('state')!='passed_class_modes_exact_K_model_conversion_exports_protection_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 not all(x.get('class_K_lock_enforced') and x.get('wrong_K_server_save_rejected') for x in ui.get('viewports',[]))):
        raise ValueError('Independent source/point/export and actual locked-K browser acceptance required')
    extension=read_json(EXTENSION/'editor_extension_manifest.json')
    extension_verification=read_json(EXTENSION/'verification.json')
    add_ui=read_json(EXTENSION/'ui_acceptance/ui_acceptance.json')
    if (extension.get('initial_worklist_manifest_sha256')!=digest(ROOT/'manifest.json')
            or extension_verification.get('state')!='passed_editor_add_point_extension_initial_K_unchanged_and_real_history_preserved'
            or extension_verification.get('editor_extension_manifest_sha256')!=digest(EXTENSION/'editor_extension_manifest.json')
            or add_ui.get('state')!='passed_actual_headless_Chromium_isolated_fullflow_not_real_Safari'
            or add_ui.get('manifest_sha256')!=digest(ROOT/'manifest.json') or add_ui.get('production_annotation_writes')!=0
            or len(add_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') for x in add_ui.get('viewports',[]))):
        raise ValueError('Actual temporary-store add-point/save/reload browser acceptance required before reload')
    value=dict(schema='class_modal_keypoint_review_runtime_v1',task_directory=str(ROOT.relative_to(PROJECT)),
        review_directory=str(REVIEWS.relative_to(PROJECT)),manifest_sha256=digest(ROOT/'manifest.json'),
        source_namespace='model-class-keypoints-v3',request_count=m['request_count'],class_standard_sha256=m['class_standard_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('Cannot rebind an existing class-keypoint service')
    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')=='model-class-keypoints-v3' and v.get('targets')==read_json(ROOT/'manifest.json')['request_count'] and v.get('editing_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=ClassKeypointGallery(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('Dedicated port/tunnel unavailable; old services untouched')
    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='model-class-keypoints-v3',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 is occupied; no old service will be stopped')
    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('Class-keypoint service failed; its log is preserved')
        time.sleep(1)
    raise RuntimeError('New endpoint 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())))
