"""Round5 transport-only adapter; original verified app and task store unchanged."""
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

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT));sys.path.insert(0,str(PROJECT/'scripts'))
from pallet.mask_model_training_data import read,require
from pallet.pallet_review_ptunnel import PTUNNEL,profiles,profile_name,validate_route
from pallet.pallet_description_round5_release import REVIEW_SETS
from serve_pallet_description_round5 import runtime_for
from serve_structure_review import Child,process_identity,timestamp,write_json


def route_status(mode,settings):
    row=profiles().get(profile_name(mode));require(row is not None,'Configured ptunnel profile missing; no Cloudflare fallback')
    return validate_route(row,mode=mode,port=settings['port'])


def port_available(port):
    # Match HTTPServer.allow_reuse_address; closed old HTTP connections may be
    # in TIME_WAIT, which is not a live competing listener.
    with socket.socket() as sock:
        sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
        try:sock.bind(('127.0.0.1',port));return True
        except OSError:return False


def make_runtime(mode):
    runtime=runtime_for(mode);s=REVIEW_SETS[mode];state=s['managed'];base_configure=runtime.configure
    runtime.available=lambda:port_available(s['port'])
    def configure():
        base_configure();pointer=read(state/'transport.json')
        require(pointer.get('provider')=='ptunnel' and pointer.get('profile')==profile_name(mode) and pointer.get('port')==s['port'],'Invalid transport binding')
        require(pointer.get('allow_cloudflare_fallback') is False,'Cloudflare fallback must stay disabled')
        require(PTUNNEL.is_file(),'Installed ptunnel executable required')
        route_status(mode,s)
    def supervise():
        configure();require(runtime.available(),'App port already occupied; do not replace existing process')
        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(PROJECT/f'scripts/serve_pallet_description_round5_{mode}.py'),'app'],state,env)
            stop=threading.Event();started=timestamp();identity=process_identity(os.getpid());previous=None;next_probe=0.;row=None;error=None;app_ready=False
            for sig in (signal.SIGTERM,signal.SIGINT):signal.signal(sig,lambda *_:stop.set())
            def persist(status):
                value=dict(state=status,pid=os.getpid(),process_identity=identity,started_at=started,updated_at=timestamp(),app=child.status(),
                    tunnel=dict(provider='ptunnel',profile=profile_name(mode),managed_by='existing_ptunnel_client_daemon',status=row.get('status') if row else 'unknown'),
                    public_url=row.get('url') if row else None,local_url=runtime.LOCAL,tunnel_connected=bool(row and row.get('status')=='connected'),
                    child_autorestart=True,boot_autostart_configured=False,temporary_url=False,hostname_persistence='ptunnel_saved_profile_not_permanence_guarantee',
                    task_directory=str(s['root'].relative_to(PROJECT)),manifest_sha256=read(state/'runtime.json')['manifest_sha256'],
                    source_namespace=s['namespace'],editing_enabled=True,isolated_review_directory=str(s['reviews'].relative_to(PROJECT)),
                    transport_provider='ptunnel',allow_cloudflare_fallback=False,transport_error=error)
                write_json(state/'supervisor.json',value);write_json(state/'public_access.json',value)
            persist('starting')
            try:
                while not stop.is_set():
                    changed=child.ensure();now=time.monotonic()
                    if now>=next_probe:
                        next_probe=now+5
                        try:
                            row=route_status(mode,s);error=None
                        except (OSError,ValueError,subprocess.SubprocessError):
                            row=None;error='ptunnel_profile_status_unavailable_no_cloudflare_fallback'
                        app_ready=runtime.healthy()
                        marker=(row.get('url'),row.get('status'),app_ready) if row else (None,error,app_ready)
                        changed=changed or marker!=previous;previous=marker
                    if changed:persist('connected' if row and row.get('status')=='connected' and app_ready else 'reconnecting')
                    stop.wait(1)
            finally:
                child.stop();persist('stopped')
                # The shared daemon and saved profiles outlive the app supervisor.
                # Never shutdown the client or delete a route here.
    def start(timeout):
        current=runtime.running()
        if current:
            require(current.get('transport_provider')=='ptunnel','Old Cloudflare supervisor is still active; perform verified migration first')
            print(json.dumps(dict(current,already_running=True)));return
        configure();require(runtime.available(),'App port occupied; no unrelated process stopped')
        with (state/'supervisor_ptunnel.log').open('ab') as log:
            process=subprocess.Popen([sys.executable,str(PROJECT/f'scripts/serve_pallet_description_round5_{mode}.py'),'run'],cwd=PROJECT,
                stdin=subprocess.DEVNULL,stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
        deadline=time.monotonic()+timeout
        while time.monotonic()<deadline:
            current=runtime.running()
            if current and current['pid']==process.pid and current.get('transport_provider')=='ptunnel' and current.get('tunnel_connected') and runtime.healthy():
                print(json.dumps(current));return
            if process.poll() is not None:raise RuntimeError('ptunnel app supervisor failed; preserved logs require inspection')
            time.sleep(1)
        raise RuntimeError('ptunnel app still starting; do not recreate route')
    runtime.configure=configure;runtime.supervise=supervise;runtime.start=start;return runtime


def main(mode):
    require((REVIEW_SETS[mode]['managed']/'transport.json').exists(),'ptunnel configuration required; Cloudflare fallback is disabled')
    parser=argparse.ArgumentParser();parser.add_argument('command',choices=('app','run','start','status'));parser.add_argument('--timeout',type=int,default=180);args=parser.parse_args()
    runtime=make_runtime(mode)
    if args.command=='app':
        if (REVIEW_SETS[mode]['managed']/'terms_policy.json').exists():
            from serve_pallet_description_terms import app
            app(mode,runtime)
        else:runtime.app()
    elif args.command=='run':runtime.supervise()
    elif args.command=='start':runtime.start(args.timeout)
    else:print(json.dumps(dict(supervisor=runtime.running(),healthy=runtime.healthy())))
