"""Separate managed editor for rejected-quality examples; no canonical writes."""
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.cluster_targets import digest
from pallet.mask_nonconforming_review import NonconformingGallery, NonconformingHandler
from serve_structure_review import Child, process_identity, read_json, write_json, timestamp

TASKS = PROJECT/'outputs/pallet_mask_nonconforming_requests_v1'
STATE = PROJECT/'outputs/pallet_mask_nonconforming_managed_v1'
REVIEWS = PROJECT/'outputs/pallet_mask_nonconforming_reviews_v1'
PORT = 3401
LOCAL = 'http://127.0.0.1:3401'
CLOUDFLARED = Path('/tmp/opencode/pallet_review_tunnel/cloudflared')


def require(value, message):
    if not value:
        raise ValueError(message)


def configure():
    manifest, seal = read_json(TASKS/'manifest.json'), read_json(TASKS/'verification.json')
    require(seal['state'] == 'passed_export_and_isolation_not_quality' and seal['manifest_sha256'] == digest(TASKS/'manifest.json'), 'Rejected-quality structural seal required')
    for name, expected in manifest['code_sha256'].items():
        require(digest(PROJECT/name) == expected, 'Pinned nonconforming implementation changed')
    STATE.mkdir(mode=0o700, exist_ok=True)
    value = dict(schema='nonconforming_review_runtime_v1', task_directory=str(TASKS.relative_to(PROJECT)),
        review_directory=str(REVIEWS.relative_to(PROJECT)), task_manifest_sha256=digest(TASKS/'manifest.json'),
        request_count=7, counts_toward_under50=False, qualified_preannotations=0,
        shares_production_mask_store=False, user_authorization='本次按照不合格标注提供')
    path = STATE/'runtime.json'
    if path.exists():
        require(read_json(path) == value, 'Never silently rebind a running exception endpoint')
    else:
        with path.open('x') as stream:
            json.dump(value, stream, ensure_ascii=False)
        path.chmod(0o600)
    return value


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


def healthy():
    try:
        with urlopen(LOCAL+'/healthz', timeout=3) as response:
            value = json.load(response)
        return value.get('service') == 'pallet_mask_nonconforming_review' and value.get('targets') == 7 and value.get('counts_toward_under50') is False
    except (OSError, ValueError):
        return False


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


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


def supervise():
    configure(); require(CLOUDFLARED.is_file() and available(), 'New port unavailable; old services are never replaced')
    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)
        stopped = threading.Event(); started = timestamp(); identity = process_identity(os.getpid())
        for sig in (signal.SIGTERM, signal.SIGINT):
            signal.signal(sig, lambda *_: stopped.set())
        def persist(status):
            value = 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, temporary_url=True, boot_autostart_configured=False, source_quality='nonconforming',
                editing_enabled=True, isolated_review_directory=str(REVIEWS.relative_to(PROJECT)), shares_production_mask_store=False,
                counts_toward_under50=False, qualified_preannotations=0, old_services_or_configs_modified=False,
                task_directory=str(TASKS.relative_to(PROJECT)), task_manifest_sha256=digest(TASKS/'manifest.json'))
            write_json(STATE/'supervisor.json', value); write_json(STATE/'public_access.json', value)
        persist('starting')
        try:
            while not stopped.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')
                stopped.wait(1)
        finally:
            tunnel.stop(); child.stop(); tunnel.connected = False; persist('stopped')


def start(timeout):
    value = running()
    if value:
        print(json.dumps(dict(value, already_running=True))); return
    configure(); require(available(), 'Dedicated port occupied; leave other services intact')
    with (STATE/'supervisor.log').open('ab') as log:
        process = subprocess.Popen([sys.executable, str(Path(__file__).resolve()), '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:
        value = running()
        if value and value['pid'] == process.pid and value.get('tunnel_connected') and healthy():
            print(json.dumps(value)); return
        if process.poll() is not None:
            raise RuntimeError('New isolated supervisor failed; preserve its log')
        time.sleep(1)
    raise RuntimeError('Dedicated service still starting; no old service restarted')


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