"""Independent managed anomaly decisions; existing label/report services untouched."""
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_anomaly_review import Application, Handler
from serve_structure_review import Child, process_identity, read_json, write_json, timestamp

ROOT = PROJECT/'outputs/pallet_mask_anomaly_human_review_package_v1'
STATE = PROJECT/'outputs/pallet_mask_anomaly_review_managed_v1'
REVIEWS = PROJECT/'outputs/pallet_mask_anomaly_human_reviews_v1'
PORT = 3404
LOCAL = 'http://127.0.0.1:3404'
CLOUDFLARED = Path('/tmp/opencode/pallet_review_tunnel/cloudflared')


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


def configure():
    manifest = read_json(ROOT/'manifest.json')
    require(manifest.get('schema') == 'human_anomaly_review_package_v1'
        and manifest.get('target_count') == 455 and manifest.get('class_atlas_count') == 22
        and manifest.get('current_model_anomalies') == 23 and manifest.get('automatic_label_application') is False,
        'Frozen455/22 visual anomaly-review package required')
    seal_path = PROJECT/'outputs/pallet_mask_anomaly_review_readonly_verification_v1.json'
    ui_path = PROJECT/'outputs/pallet_mask_anomaly_review_ui_acceptance_v3/acceptance.json'
    seal, ui = read_json(seal_path), read_json(ui_path)
    require(seal.get('state') == 'passed_readonly_recomputed_sources_images_and_protection_not_semantic_class_certification'
        and seal.get('package_sha256') == digest(ROOT/'manifest.json'), 'Matching read-only recomputation required')
    require(ui.get('state') == 'passed_local_chromium_DOM_events_not_pointer_or_visual_rendering_certification'
        and ui.get('package_sha256') == digest(ROOT/'manifest.json') and ui.get('production_saves') == 0,
        'Matching isolated UI functional acceptance required')
    for name, expected in manifest['source_code_sha256'].items():
        require(digest(PROJECT/name) == expected, 'Pinned anomaly review implementation differs; use a new package')
    STATE.mkdir(mode=0o700, exist_ok=True)
    value = dict(schema='isolated_anomaly_review_runtime_v1', package=str(ROOT.relative_to(PROJECT)),
        review_directory=str(REVIEWS.relative_to(PROJECT)), package_sha256=digest(ROOT/'manifest.json'),
        targets=455, classes=22, current_model_priority=23, automatic_label_application=False,
        changes_masks_or_training=False, production_mask_store_shared=False,
        source_verification_sha256=digest(seal_path), isolated_ui_acceptance_sha256=digest(ui_path))
    path = STATE/'runtime.json'
    if path.exists():
        require(read_json(path) == value, 'Do not silently rebind a live anomaly-review endpoint')
    else:
        with path.open('xb') as stream:
            from pallet.pose_review_geometry import canonical
            stream.write(canonical(value)+b'\n')
        path.chmod(0o600)
    return value


def app():
    configure()
    key = (PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    application = Application(ROOT, REVIEWS, key)
    server = ThreadingHTTPServer(('127.0.0.1', PORT), Handler); server.daemon_threads = True; server.app = application
    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_anomaly_human_review' and value.get('targets') == 455 \
            and value.get('classes') == 22 and value.get('labels_automatically_applied') 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 dedicated port unavailable; old services unchanged')
    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, boot_autostart_configured=False, temporary_url=True,
                decision_writes_enabled=True, labels_automatically_applied=False, production_mask_store_shared=False,
                review_directory=str(REVIEWS.relative_to(PROJECT)), package=str(ROOT.relative_to(PROJECT)),
                package_sha256=digest(ROOT/'manifest.json'), old_services_or_configs_modified=False)
            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(), 'New anomaly-review port occupied; no existing services replaced')
    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 anomaly-review supervisor failed; preserve its logs')
        time.sleep(1)
    raise RuntimeError('New service still starting; existing URLs remain intact')


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())))
