"""Separate small-batch review app/tunnel; never reloads existing review services."""
import argparse
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)); sys.path.insert(0, str(PROJECT/'scripts'))
from pallet.cluster_targets import digest
from pallet.mask_gallery import Gallery, GalleryServer
from pallet.pose_review_geometry import canonical
from serve_structure_review import Child, process_identity, read_json, write_json, timestamp

ROOT = PROJECT/'outputs/pallet_mask_remaining_round5_v1'
TASKS = PROJECT/'outputs/pallet_mask_under50_requests_v1'
STATE = PROJECT/'outputs/pallet_mask_under50_managed_v1'
CONFIG = STATE/'requests_config.json'
PORT = 3395
LOCAL = f'http://127.0.0.1:{PORT}'
CLOUDFLARED = Path('/tmp/opencode/pallet_review_tunnel/cloudflared')


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


def configure():
    """Only a fresh runtime config, outside global configs and immutable tasks."""
    manifest = read_json(TASKS/'manifest.json'); seal = read_json(TASKS/'verification.json')
    require(seal.get('state') == 'passed' and seal.get('preannotations_verified') is True
        and seal['manifest_sha256'] == digest(TASKS/'manifest.json')
        and digest(TASKS/'verification.json') == digest(TASKS/'independent_verification.json'),
        'Independent preannotation seal required')
    value = dict(schema='preannotated_mask_worklist_v1', directory=str(TASKS.relative_to(PROJECT)),
        manifest_sha256=digest(TASKS/'manifest.json'), verification_sha256=digest(TASKS/'verification.json'),
        request_count=manifest['request_count'], completed_request_count=0,
        requested_classes=manifest['classes'], target_per_class=50, counts_as_completed_annotation=False,
        user_authorization='执行模型方案；训练期间为真实人工轮廓少于50份的类别补充新图预标注供人工复核')
    if CONFIG.exists():
        require(read_json(CONFIG) == value, 'Do not replace a runtime task binding')
    else:
        STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
        with CONFIG.open('xb') as stream:
            stream.write(canonical(value)+b'\n')
    return value


def app():
    configure()
    key = (PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    gallery = Gallery(ROOT, PROJECT/'outputs/pallet_mask_gallery_reviews_v1', key, requests_config=CONFIG)
    # Runtime-only scope notice, like the existing editor fragment: the sealed
    # task page and all old task pages remain byte-for-byte unchanged.
    notice = ('<p id="under50ScopeNote" style="padding:12px;border:1px solid #85bdda">'
        '本批只新增10张待复核草稿。Class 12的3张备选因强反光/缺测边界全部暂缓，没有凑数；'
        '本批保存不回写位姿，也不自动加入当前训练。旧图库及上一批26张入口继续保留。</p>')
    gallery.request_page = gallery.request_page.replace(b'</h1>', b'</h1>'+notice.encode('utf-8'), 1)
    server = GalleryServer(('127.0.0.1', PORT), gallery)
    logging.basicConfig(level=logging.INFO)
    try:
        server.serve_forever()
    finally:
        server.server_close()


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


def healthy():
    try:
        with urlopen(LOCAL+'/healthz', timeout=2) as response:
            health = json.load(response)
            return (health.get('service') == 'pallet_mask_gallery' and health.get('publication_version') == 15
                and health.get('editing_enabled') is True and health.get('manual_template_requests') == read_json(CONFIG).get('request_count'))
    except (OSError, ValueError):
        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(), 'Missing tunnel or occupied port; existing processes preserved')
    with (STATE/'supervisor.lock').open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
        environment = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1', PYTHONDONTWRITEBYTECODE='1')
        child = Child('app', [sys.executable, str(Path(__file__).resolve()), 'app'], STATE, environment)
        tunnel = Child('tunnel', [str(CLOUDFLARED), 'tunnel', '--no-autoupdate', '--url', LOCAL, '--protocol', 'http2'], STATE, environment)
        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, editing_enabled=True,
                authentication_required_for_editing=True, old_services_or_configs_modified=False,
                task_directory=str(TASKS.relative_to(PROJECT)), task_manifest_sha256=digest(TASKS/'manifest.json'),
                gallery_publication=15, shared_mask_history='outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3')
            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):
    previous = running()
    if previous:
        print(json.dumps(dict(previous, already_running=True))); return
    configure(); require(available(), 'Supplementary port occupied; no existing processes changed')
    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)
    # Readiness of this newly launched managed service, not a training-job poll.
    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('Supplementary supervisor failed; inspect its own log, do not restart old services')
        time.sleep(1)
    raise RuntimeError('New service is still starting; preserve all old service processes')


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