"""Independent single-instance pose editor and Cloudflare Quick Tunnel supervisor."""
from __future__ import annotations

import argparse
from datetime import datetime, timezone
import fcntl
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/'scripts'))
from serve_structure_review import Child, process_identity, read_json, write_json

STATE=PROJECT/'outputs/pallet_pose_review_managed_v1'
PUBLIC=STATE/'public_access.json'
CLOUDFLARED=Path('/tmp/opencode/pallet_review_tunnel/cloudflared')
LOCAL='http://127.0.0.1:3390'


def timestamp(): return datetime.now(timezone.utc).isoformat(timespec='seconds')


def health():
    try:
        with urlopen(LOCAL+'/healthz',timeout=2) as response:
            return response.status==200 and json.load(response).get('service')=='pallet_pose_review'
    except (OSError,ValueError): return False


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


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


def supervise():
    STATE.mkdir(parents=True,exist_ok=True)
    logging.basicConfig(level=logging.INFO,format='%(asctime)s %(levelname)s %(message)s')
    with (STATE/'supervisor.lock').open('a') as lock:
        fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
        if not CLOUDFLARED.is_file(): raise SystemExit('Cloudflared binary missing')
        if not available(): raise SystemExit('3390 is occupied; no existing process was changed')
        old=read_json(PUBLIC)
        write_json(STATE/('previous_access_'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')+'.json'),old)
        env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1',PYTHONUNBUFFERED='1')
        app=Child('app',[sys.executable,'-m','pallet.pose_review','--host','127.0.0.1','--port','3390'],STATE,env)
        tunnel=Child('tunnel',[str(CLOUDFLARED),'tunnel','--no-autoupdate','--url',LOCAL,'--protocol','http2'],STATE,env)
        stopped=threading.Event()
        for sig in (signal.SIGTERM,signal.SIGINT): signal.signal(sig,lambda *_:stopped.set())
        identity=process_identity(os.getpid()); started=timestamp()
        def persist(status):
            value={'state':status,'pid':os.getpid(),'process_identity':identity,'started_at':started,
                'updated_at':timestamp(),'app':app.status(),'tunnel':tunnel.status(),'public_url':tunnel.url,
                'tunnel_connected':tunnel.connected,'local_url':LOCAL,'child_autorestart':True,
                'boot_autostart_configured':False}
            write_json(STATE/'supervisor.json',value)
            write_json(PUBLIC,dict(value,tunnel_type='cloudflare_quick_tunnel',temporary_url=True,
                previous_public_url=old.get('public_url'),access_key_file='outputs/pallet_pose_human_review_v1/access_key.txt'))
        persist('starting')
        try:
            while not stopped.is_set():
                changed=app.ensure()
                if tunnel.process is not None or health(): changed=tunnel.ensure() or changed
                changed=tunnel.read_tunnel_status() or changed
                if changed: persist('connected' if tunnel.connected and health() else 'reconnecting')
                stopped.wait(1)
        finally:
            tunnel.stop();app.stop();tunnel.connected=False;persist('stopped')


def start(timeout):
    state=running()
    if state: print(json.dumps(dict(state,already_running=True),ensure_ascii=False));return
    if not available(): raise SystemExit('3390 is occupied; no process was changed')
    if not CLOUDFLARED.is_file(): raise SystemExit('Cloudflared binary missing')
    STATE.mkdir(parents=True,exist_ok=True)
    with (STATE/'supervisor.log').open('ab') as log:
        process=subprocess.Popen([sys.executable,str(Path(__file__).absolute()),'run'],cwd=PROJECT,
            stdin=subprocess.DEVNULL,stdout=log,stderr=subprocess.STDOUT,start_new_session=True,close_fds=True)
    deadline=time.monotonic()+timeout
    while time.monotonic()<deadline:
        state=running()
        if state and state['pid']==process.pid and state.get('tunnel_connected') and health():
            print(json.dumps(state,ensure_ascii=False));return
        if process.poll() is not None: raise SystemExit('Startup failed; see '+str(STATE/'supervisor.log'))
        time.sleep(1)
    raise SystemExit('Service is still starting; see '+str(STATE/'supervisor.json'))


def stop():
    state=running()
    if not state: print('No active pose supervisor');return
    os.kill(state['pid'],signal.SIGTERM)
    print('Stop requested for the pose editor/tunnel only')


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('command',choices=('start','run','status','stop'));parser.add_argument('--timeout',type=int,default=120)
    args=parser.parse_args()
    if args.command=='run': supervise()
    elif args.command=='start': start(args.timeout)
    elif args.command=='stop': stop()
    else: print(json.dumps({'supervisor':running(),'local_http_healthy':health()},ensure_ascii=False))
