"""Dedicated3420/3421, saved ptunnel profiles only; never rebind completed round5."""
import argparse
import fcntl
from http.server import ThreadingHTTPServer
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
import threading
import time
from urllib.parse import urlsplit
from urllib.request import urlopen
import xml.etree.ElementTree as ET

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_model_training_data import read,write,require
from pallet.pallet_description_round6_data import ROOT,binding_guard,sources_current
from pallet.pallet_description_round6_release import REVIEW_SETS,RELEASE,bind_review_sets
from pallet.pallet_description_review import JointGallery
from pallet.pallet_review_ptunnel import PTUNNEL,profiles,command
from serve_pallet_description_terms import TermsHandler
from serve_pallet_description_ptunnel import port_available
from serve_structure_review import Child,process_identity,timestamp,write_json

CODE=('pallet/pallet_description_round6_data.py','pallet/pallet_description_round6_mask.py','pallet/pallet_description_round6_vlm.py','pallet/pallet_description_round6_release.py',
    'scripts/serve_pallet_description_round6.py','scripts/serve_pallet_description_round6_new.py','scripts/serve_pallet_description_round6_existing.py',
    'scripts/check_pallet_description_round6_ui.py','scripts/finalize_pallet_description_round6.py','tests/test_pallet_description_round6.py')


def configure(mode):
    s=REVIEW_SETS[mode];overlay=RELEASE/mode;manifest=read(s['root']/'manifest.json');seal=read(s['root']/'verification.json')
    ui=read(overlay/'round6_browser_verification.json')
    require(seal['state']=='passed_joint_description_source_K_and_no_old_image_reuse' and seal['manifest_sha256']==digest(s['root']/'manifest.json'),'Task/strictK verification required')
    require(ui['state']=='passed_round6_actual_task_desktop390_all_batch_and_fast_navigation' and ui['production_annotation_POSTs']==0 and not ui['page_errors'],'Actual round6 browser verification required')
    require(ui['task_manifest_sha256']==digest(s['root']/'manifest.json') and ui['overlay_manifest_sha256']==digest(overlay/'manifest.json'),'Tested task/UI changed')
    require(set(ui['implementation_sha256'])==set(CODE) and all(digest(PROJECT/n)==h for n,h in ui['implementation_sha256'].items()),'Tested round6 implementation changed')
    require(all(digest(PROJECT/n)==h for n,h in ui['base_implementation_sha256'].items()),'Tested base editor changed')
    require(all(digest(overlay/'adapted_test_code'/n)==h for n,h in ui['adapted_test_sources'].items()),'Actual test sources changed')
    require(digest(ROOT/f'browser_performance/{mode}/navigation_benchmark.json')==ui['navigation_performance_sha256'],'Actual navigation evidence changed')
    require(read(overlay/'checks/all_targets.json')['state']=='passed_all_actual_targets_terms_apply_and_replay','Whole-sequence verification required')
    suites=ET.parse(ROOT/'regressions_final.xml').getroot().findall('testsuite')
    require(sum(int(v.attrib['tests']) for v in suites)>=280 and not sum(int(v.attrib.get(k,0)) for v in suites for k in ('errors','failures','skipped')),'Round6 CPU regressions required')
    require(read(ROOT/'training_verification.json')['state']=='round6_actual_training_and_latest_source_replay_passed','Actual training audit required')
    require(digest(s['root']/'proposals.jsonl')==manifest['proposals_sha256'] and sources_current(),'Frozen source changed')
    require(all(digest(overlay/n)==h for n,h in read(overlay/'manifest.json')['assets'].items()),'Tested assets changed')
    s['managed'].mkdir(mode=0o700,exist_ok=True)
    expected=dict(namespace=s['namespace'],port=s['port'],task_directory=str(s['root'].relative_to(PROJECT)),review_directory=str(s['reviews'].relative_to(PROJECT)),manifest_sha256=digest(s['root']/'manifest.json'))
    path=s['managed']/'runtime.json'
    if path.exists():require(read(path)==expected,'Refuse task/namespace rebind')
    else:write(path,expected)


def profile(mode):return 'pallet-description-round6-'+mode


def validate_route(row,mode):
    s=REVIEW_SETS[mode];url=urlsplit(row.get('url') or '')
    require(row.get('id')==profile(mode) and row.get('type')=='http' and row.get('host')=='127.0.0.1' and row.get('port')==s['port'] and row.get('target')==f'127.0.0.1:{s["port"]}','Wrong round6 ptunnel binding')
    require(url.scheme=='https' and url.hostname and url.hostname.endswith('.tunnel.phineas.top') and not url.username and not url.password and not url.port and url.path in ('','/') and not url.query and not url.fragment,'Wrong ptunnel public URL')
    return row


def route(mode):
    rows=profiles();require(profile(mode) in rows,'Saved round6 ptunnel profile required; no Cloudflare fallback')
    return validate_route(rows[profile(mode)],mode)


def provision(mode):
    configure(mode);require(PTUNNEL.is_file(),'Installed authenticated ptunnel required');name=profile(mode);s=REVIEW_SETS[mode]
    require(port_available(s['port']) or healthy(mode),'Refuse to publish a port occupied by an unrelated service')
    before=profiles()
    if name in before:row=validate_route(before[name],mode)
    else:row=validate_route(command(['http',str(s['port']),'--host','127.0.0.1','--name',name,'--json'],timeout=260),mode)
    require(row.get('status')=='connected','Saved profile reconnecting; inspect, do not recreate')
    after=profiles();require(all(all(after[k].get(f)==v.get(f) for f in ('id','host','port','target','url','tunnelID')) for k,v in before.items()),'Unrelated profile changed')
    path=s['managed']/'transport.json';value=dict(provider='ptunnel',profile=name,port=s['port'],allow_cloudflare_fallback=False,public_url=row['url'])
    if path.exists():require(read(path)==value,'Refuse transport/profile rebind')
    else:write(path,value)
    print(json.dumps(dict(mode=mode,public_url=row['url'],profile=name)))


def configured_route(mode):
    s=REVIEW_SETS[mode];pointer=read(s['managed']/'transport.json');row=route(mode)
    require(pointer==dict(provider='ptunnel',profile=profile(mode),port=s['port'],allow_cloudflare_fallback=False,public_url=row['url']),'Transport pointer changed')
    return row


def healthy(mode):
    s=REVIEW_SETS[mode]
    try:
        with urlopen(f'http://127.0.0.1:{s["port"]}/healthz',timeout=4) as response:h=json.load(response)
        return h['publication_version']==s['namespace'] and h['targets']==read(s['root']/'manifest.json')['request_count'] and h['structure_terms_batch_enabled'] and h['source_guard']['parallel_full_content']
    except (OSError,ValueError,KeyError):return False


def running(mode):
    path=REVIEW_SETS[mode]['managed']/'supervisor.json'
    if not path.exists():return None
    value=read(path)
    return value if type(value.get('pid'))is int and value.get('process_identity') and value.get('state')!='stopped' and value['process_identity']==process_identity(value['pid']) else None


def app(mode):
    configure(mode);configured_route(mode);bind_review_sets();s=REVIEW_SETS[mode];key=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    g=JointGallery(mode,key=key,guard=binding_guard(),presentation=RELEASE/mode);g.structure_terms_batch_enabled=True
    server=ThreadingHTTPServer(('127.0.0.1',s['port']),TermsHandler);server.gallery=g;server.daemon_threads=True
    try:server.serve_forever()
    finally:server.server_close();g.close()


def supervise(mode):
    configure(mode);configured_route(mode);s=REVIEW_SETS[mode];state=s['managed'];require(port_available(s['port']),'App port already occupied')
    with (state/'supervisor.lock').open('a') as lock:
        fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
        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_round6_{mode}.py'),'app'],state,env)
        stop=threading.Event();started=timestamp();identity=process_identity(os.getpid());previous=None;next_probe=0.;row=None;error=None;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(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=f'http://127.0.0.1:{s["port"]}',tunnel_connected=bool(row and row.get('status')=='connected'),
                child_autorestart=True,boot_autostart_configured=False,temporary_url=False,hostname_persistence='saved_profile_not_permanence_guarantee',
                task_directory=str(s['root'].relative_to(PROJECT)),source_namespace=s['namespace'],editing_enabled=True,isolated_review_directory=str(s['reviews'].relative_to(PROJECT)),
                manifest_sha256=digest(s['root']/'manifest.json'),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=configured_route(mode);error=None
                    except (OSError,ValueError,subprocess.SubprocessError):row=None;error='saved_ptunnel_profile_unavailable_no_fallback'
                    ready=healthy(mode);marker=(row.get('url'),row.get('status'),ready) if row else (None,error,ready)
                    changed=changed or marker!=previous;previous=marker
                if changed:persist('connected' if row and row.get('status')=='connected' and ready else 'reconnecting')
                stop.wait(1)
        finally:child.stop();persist('stopped')


def start(mode,timeout):
    current=running(mode)
    if current:print(json.dumps(dict(current,already_running=True)));return
    configure(mode);configured_route(mode);s=REVIEW_SETS[mode];require(port_available(s['port']),'App port occupied; no process stopped')
    with (s['managed']/'supervisor_ptunnel.log').open('ab') as log:
        process=subprocess.Popen([sys.executable,str(PROJECT/f'scripts/serve_pallet_description_round6_{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=running(mode)
        if current and current['pid']==process.pid and current.get('state')=='connected' and healthy(mode):print(json.dumps(current));return
        if process.poll() is not None:raise RuntimeError('Round6 supervisor failed; inspect preserved logs')
        time.sleep(1)
    raise RuntimeError('Round6 app still starting; do not recreate saved profile')


def main(mode):
    p=argparse.ArgumentParser();p.add_argument('command',choices=('provision','app','run','start','status'));p.add_argument('--timeout',type=int,default=180);args=p.parse_args()
    if args.command=='provision':provision(mode)
    elif args.command=='app':app(mode)
    elif args.command=='run':supervise(mode)
    elif args.command=='start':start(mode,args.timeout)
    else:print(json.dumps(dict(supervisor=running(mode),healthy=healthy(mode))))
