#!/usr/bin/env python3
"""One explicitly approved, exact-owned Oracle8 lease. No other Docker resources."""
import datetime, json, os, pathlib, secrets, socket, subprocess, sys, time

ROOT = pathlib.Path('/mnt/k/AI_docs_tmp/nuhet-3967-editor/rev8/oracle8')
PROJECT = pathlib.Path('/var/www/nuhet-editor-ui-3967')
IMAGE = 'mysql@sha256:8b8835a2c32cd7357a5d2ea4b49ad870ff519c8c1d4add362803feddf4a0a973'
OWNER = 'p_0ddf8d43ba8a'
ENV = {k: os.environ[k] for k in ('PATH','LANG','LC_ALL','TZ','TMPDIR') if k in os.environ}
ENV['DOCKER_CONTEXT'] = 'default'
SETUP_DEADLINE = None
OVERALL_DEADLINE = None
FINAL_GRANT = 'r8-oracle8-final-20261019-074708'

def run(args, timeout=30, check=True):
    active=[x for x in (SETUP_DEADLINE,OVERALL_DEADLINE) if x is not None]
    if active:
        remaining=min(active)-time.time()
        if remaining<=0: raise RuntimeError('Absolute Oracle8 setup expiry or recovery expiry reached before launch')
        timeout=min(timeout,remaining)
    p = subprocess.run(args, env=ENV, cwd=PROJECT, capture_output=True, text=True, timeout=timeout)
    if active and time.time()>=min(active): raise RuntimeError('Absolute Oracle8 setup expiry or recovery expiry reached at completion; reconcile effects')
    if check and p.returncode:
        raise RuntimeError('Command failed: '+args[0]+' '+args[1]+'; '+p.stderr[:400])
    return p

def docker(*args, **kwargs): return run(['docker','--context','default',*args], **kwargs)
def inspect(kind, name, template):
    p=docker(kind,'inspect',name,'--format',template,check=False)
    if p.returncode:
        if 'no such' in p.stderr.lower(): return None
        raise RuntimeError('Exact inspect unavailable')
    return p.stdout.strip()
def utc(): return datetime.datetime.now(datetime.timezone.utc).isoformat()
def write(path, value): path.write_text(json.dumps(value,indent=2)+'\n')

def watchdog(receipt):
    path=pathlib.Path(receipt)
    if path.parent!=ROOT or not path.name.startswith('runtime-'): return 1
    r=json.loads(path.read_text()); cid=r['container_id']; deadline=r['lease_expiry']-15
    while time.time()<deadline:
        value=inspect('container',cid,'{{.State.Running}}')
        if value is None or value=='false': return 0
        try: os.kill(r['controller_pid'],0)
        except ProcessLookupError: break
        time.sleep(min(5,max(0,deadline-time.time())))
    raw=inspect('container',cid,'{{json .Config.Labels}}')
    if raw is not None:
        labels=json.loads(raw)
        if labels.get('nuhet.nonce')!=r['nonce'] or labels.get('nuhet.owner')!=OWNER: return 1
        if inspect('container',cid,'{{.State.Running}}')=='true': docker('stop','--time','10',cid,timeout=25)
    write(ROOT/('watchdog-'+r['nonce']+'.json'),{'stopped_exact_container':cid,'at':utc(),'reason':'lease_or_controller_absent'})
    return 0
def cleanup_mapping(value):
    if isinstance(value,dict): return dict(value)
    if value==[]: return {}
    raise RuntimeError('Invalid cleanup mapping; refuse coercion')

def final_admission(records, claim_exists, now):
    actual=[r for r in records if r.get('first_started_at')]
    expected={'b24b935fe101397c','bbe9584fcefcbe27'}
    if claim_exists or any(r.get('authorization')==FINAL_GRANT for r in records): raise RuntimeError('Final allocation claim consumed; no fourth or replacement')
    if len(actual)!=2 or {r['nonce'] for r in actual}!=expected: raise RuntimeError('Exactly the two preserved prior actual runtimes required')
    if now<1792396028 or now>=1792396628-180: raise RuntimeError('Final grant setup admission window or reserve unavailable')
    for old in actual:
        if old['lease_expiry']!=1792395574 or old['schema_state']!='absent' or old['phase']!='cleaned' or any(not old['cleanup'].get(k) for k in ('container_absent','volume_absent','password_directory_absent','port_closed')): raise RuntimeError('Prior exact cleanup not established')
    return {'authorization':FINAL_GRANT,'attempt':3,'max_attempts':3,'prior_nonces':sorted(expected),'recovery_start':1792396028,'recovery_expiry':1792397828,'setup_expiry':1792396628,'test_stop':1792397708,'runtime_max_seconds':600,'sql_max_seconds':120}

def final_runtime_expiry(start): return min(int(start)+600,1792397708)

def final_sql_timeout(now, expiry):
    value=min(120,int(expiry-now-90),int(1792397708-now-90))
    if value<1: raise RuntimeError('No SQL budget with cleanup reserve')
    return value
def main():
    global SETUP_DEADLINE, OVERALL_DEADLINE
    SETUP_DEADLINE=1792396628; OVERALL_DEADLINE=1792397828
    if len(sys.argv)!=2 or sys.argv[1]!='--approved-final-3967-r8': raise RuntimeError('Explicit approval switch required')
    if ROOT.resolve()!=ROOT or PROJECT.resolve()!=PROJECT: raise RuntimeError('Canonical owned locations required')
    storage=json.loads((ROOT/'storage-approved-final-preflight.json').read_text())
    if storage['volume']['SizeRemaining'] < 4*1024**3 or storage['volume']['DriveLetter']!='N' or storage['disk']['Number']!=2 or storage['disk']['BusType']!='SATA' or time.time()-datetime.datetime.strptime(storage['utc'][:26],'%Y-%m-%dT%H:%M:%S.%f').replace(tzinfo=datetime.timezone.utc).timestamp()>900: raise RuntimeError('Fresh physical N storage receipt required')
    candidate=run(['git','rev-parse','HEAD']).stdout.strip()
    run(['git','merge-base','--is-ancestor','c47d3c58d9d7781c7b2131e98db6d0745fb64e25','HEAD'])
    if run(['git','branch','--show-current']).stdout.strip()!='codex/3967-editor-ui' or run(['git','status','--porcelain']).stdout.strip(): raise RuntimeError('Clean owned fixed candidate required')
    if run(['docker','context','show']).stdout.strip()!='default' or docker('context','inspect','default','--format','{{.Endpoints.docker.Host}}').stdout.strip()!='unix:///var/run/docker.sock' or os.path.realpath('/var/run/docker.sock')!='/run/docker.sock': raise RuntimeError('Exact local default context required')
    engine=docker('info','--format','{{.ID}}|{{.Name}}|{{.ServerVersion}}|{{.DockerRootDir}}|{{.OSType}}|{{.Architecture}}').stdout.strip()
    if engine!='3a2a9e09-d7db-4849-83b1-2eb2dab860e6|docker-desktop|29.4.1|/var/lib/docker|linux|x86_64': raise RuntimeError('Approved local engine changed')
    with socket.socket() as probe: probe.bind(('127.0.0.1',33967))
    records=[json.loads(p.read_text()) for p in ROOT.glob('runtime-*.json')]
    claim=ROOT/('allocation-claim-'+FINAL_GRANT+'.json')
    replacement=final_admission(records,claim.exists(),time.time())
    for old in [r for r in records if r.get('first_started_at')]:
        if inspect('container',old['container_id'],'{{.Id}}') is not None or inspect('volume',old['volume'],'{{.Name}}') is not None or pathlib.Path(old['password_file']).parent.exists() or (ROOT/('mysql-'+old['nonce'])).exists(): raise RuntimeError('Prior exact resources not absent')
        if pathlib.Path('/proc/'+str(old['watchdog_pid'])).exists() or pathlib.Path('/proc/'+str(old['controller_pid'])).exists(): raise RuntimeError('Prior controller/watchdog absence not established')
    nonce=secrets.token_hex(8); container='nuhet-editor-3967-r8-'+nonce; volume='nuhet_editor_3967_r8_'+nonce+'_data'
    secret_dir=pathlib.Path('/run/'+container); password_file=secret_dir/'password'
    record=ROOT/('runtime-'+nonce+'.json')
    state={'candidate':candidate,'owner':OWNER,'task':3967,'nonce':nonce,'schema':'nuhet_editor_3967_r8_'+nonce,'container':container,'volume':volume,'image':IMAGE,'endpoint':'127.0.0.1:33967','password_file':str(password_file),'engine':engine,'phase':'planned','schema_state':'not_allocated','created_at':utc(),'cleanup':{}}
    if replacement: state.update(replacement)
    with claim.open('x') as f: json.dump({'authorization':FINAL_GRANT,'nonce':nonce,'runtime_receipt':str(record),'candidate':candidate,'claimed_at':utc(),'max_attempts':3},f,indent=2)
    with record.open('x') as f: json.dump(state,f,indent=2)
    def save(): write(record,state)
    image_was_present=inspect('image',IMAGE,'{{.Id}}') is not None
    labels={'nuhet.task':'3967','nuhet.owner':OWNER,'nuhet.nonce':nonce}
    cid=None; volume_created=False; started=False; result=1; watcher=None
    try:
        if inspect('container',container,'{{.Id}}') is not None or inspect('volume',volume,'{{.Name}}') is not None: raise RuntimeError('Exact namespace must be absent')
        docker('pull','--platform','linux/amd64',IMAGE,timeout=300)
        image=json.loads(docker('image','inspect',IMAGE,'--format','{"id":{{json .Id}},"arch":{{json .Architecture}},"os":{{json .Os}},"digests":{{json .RepoDigests}}}').stdout)
        if image['arch']!='amd64' or image['os']!='linux' or not any(x.endswith(IMAGE.split('@')[1]) for x in image['digests']): raise RuntimeError('Pinned image identity mismatch')
        state['image_id']=image['id']; state['image_was_present']=image_was_present; save()
        secret_dir.mkdir(mode=0o700)
        fd=os.open(password_file,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
        with os.fdopen(fd,'w') as f: f.write(secrets.token_hex(32))
        label_args=[x for k,v in labels.items() for x in ('--label',k+'='+v)]
        state['volume_intent']=True;save()
        docker('volume','create',*label_args,volume);volume_created=True
        state['container_intent']=True;save()
        cid=docker('create','--name',container,'--hostname','r8-'+nonce,*label_args,'--cpus','1','--memory','1g','--restart','no','--security-opt','no-new-privileges','--mount','type=volume,source='+volume+',target=/var/lib/mysql','--mount','type=bind,source='+str(password_file)+',target=/run/editor-password,readonly','--env','MYSQL_ROOT_PASSWORD_FILE=/run/editor-password','--env','MYSQL_ROOT_HOST=%','--publish','127.0.0.1:33967:3306',IMAGE,'--character-set-server=utf8mb4','--collation-server=utf8mb4_0900_ai_ci','--sql-mode=NO_ENGINE_SUBSTITUTION','--lower-case-table-names=0','--mysqlx=OFF').stdout.strip()
        state['container_id']=cid;state['hostname']='r8-'+nonce;state['controller_pid']=os.getpid();save()
        cfg=json.loads(docker('container','inspect',cid,'--format','{"id":{{json .Id}},"image":{{json .Image}},"labels":{{json .Config.Labels}},"ports":{{json .HostConfig.PortBindings}},"mounts":{{json .Mounts}},"privileged":{{json .HostConfig.Privileged}},"restart":{{json .HostConfig.RestartPolicy.Name}},"cpu":{{json .HostConfig.NanoCpus}},"memory":{{json .HostConfig.Memory}}}').stdout)
        if cfg['id']!=cid or cfg['image']!=state['image_id'] or any(cfg['labels'].get(k)!=v for k,v in labels.items()) or cfg['ports']!={'3306/tcp':[{'HostIp':'127.0.0.1','HostPort':'33967'}]} or cfg['privileged'] or cfg['restart']!='no' or cfg['cpu']!=1000000000 or cfg['memory']!=1073741824: raise RuntimeError('Container boundary mismatch')
        if len(cfg['mounts'])!=2 or not any(m['Type']=='volume' and m['Name']==volume and m['Destination']=='/var/lib/mysql' for m in cfg['mounts']) or not any(m['Type']=='bind' and m['Destination']=='/run/editor-password' and not m['RW'] for m in cfg['mounts']): raise RuntimeError('Exact mounts required')
        state['container_boundary']=cfg;state['lease_start']=time.time();state['lease_expiry']=final_runtime_expiry(state['lease_start'])
        if replacement and time.time()>=replacement['setup_expiry']-120: raise RuntimeError('Final fixed setup expiry reserve exhausted before start')
        save()
        docker('start',cid,timeout=30);started=True;state['first_started_at']=docker('container','inspect',cid,'--format','{{.State.StartedAt}}').stdout.strip();save()
        watcher=subprocess.Popen(['python3',str(pathlib.Path(__file__).resolve()),'--watchdog',str(record)],env=ENV,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
        state['watchdog_pid']=watcher.pid;save()
        docker('exec',cid,'test','-r','/run/editor-password')
        state['bound_file_readable']=True;save()
        # Only this generated password file is read by the PDO probe; no secret arguments/output.
        until=time.monotonic()+100
        while True:
            p=run(['php','tools/newsletter-editor/oracle8-probe.php',str(record)],timeout=6,check=False)
            if p.returncode==0: break
            if p.returncode!=75 or time.monotonic()>until: raise RuntimeError('Bounded Oracle8 startup/TCP identity unavailable; probe status '+str(p.returncode))
            time.sleep(min(1,max(0,SETUP_DEADLINE-time.time())))
        identity=json.loads(p.stdout)
        if identity['version']!='8.0.34' or identity['hostname']!=state['hostname'] or identity['db'] is not None: raise RuntimeError('Fresh Oracle8 identity mismatch')
        if time.time()>=SETUP_DEADLINE: raise RuntimeError('Identity arrived after absolute setup expiry')
        state['uuid']=identity['uuid'];state['server']=identity;state['phase']='qualified';save();SETUP_DEADLINE=None
        testenv=dict(ENV,NUHET_EDITOR_3967_ORACLE8_TEST='1',NUHET_EDITOR_3967_ORACLE8_RECEIPT=str(record))
        with (ROOT/('php-oracle8-'+nonce+'.log')).open('w') as log:
            p=subprocess.run(['php','vendor/phpunit/phpunit/phpunit','--do-not-cache-result','tests/Integration/NewsletterEditorOracle8Test.php'],cwd=PROJECT,env=testenv,stdout=log,stderr=subprocess.STDOUT,timeout=final_sql_timeout(time.time(),state['lease_expiry']))
        state.update(json.loads(record.read_text()));state['cleanup']=cleanup_mapping(state['cleanup']);state['test_exit']=p.returncode;result=p.returncode;save()
        if state['schema_state']!='absent': raise RuntimeError('Owned schema cleanup not verified by test')
        if run(['git','rev-parse','HEAD']).stdout.strip()!=candidate or run(['git','status','--porcelain']).stdout.strip(): raise RuntimeError('Qualification source changed')
    except BaseException as e:
        SETUP_DEADLINE=None  # Expiry never prevents exact safe reconciliation/cleanup.
        state.update(json.loads(record.read_text()));state['cleanup']=cleanup_mapping(state['cleanup'])
        state['failure']=type(e).__name__+': '+str(e)[:600];save()
        if state.get('phase')=='qualified' and state.get('schema_state')!='absent':
            p=run(['php','tools/newsletter-editor/oracle8-probe.php',str(record),'--drop-owned'],timeout=10,check=False)
            state.update(json.loads(record.read_text()));state['cleanup']=cleanup_mapping(state['cleanup']);state['schema_reconcile_exit']=p.returncode;save()
    finally:
        SETUP_DEADLINE=None
        # Reconcile exact names after ambiguous Docker calls; never retry a mutation.
        obj=inspect('container',container,'{{json .Id}}|{{json .Config.Labels}}')
        if obj is not None:
            actual_id,raw=obj.split('|',1);actual_id=json.loads(actual_id);actual_labels=json.loads(raw)
            if any(actual_labels.get(k)!=v for k,v in labels.items()): raise RuntimeError('Refuse foreign container cleanup')
            if inspect('container',actual_id,'{{.State.Running}}')=='true': docker('stop','--time','10',actual_id,timeout=25)
            docker('rm',actual_id);state['cleanup']['container_absent']=inspect('container',actual_id,'{{.Id}}') is None
        else: state['cleanup']['container_absent']=True
        raw=inspect('volume',volume,'{{json .Labels}}')
        if raw is not None:
            if any(json.loads(raw).get(k)!=v for k,v in labels.items()): raise RuntimeError('Refuse foreign volume cleanup')
            docker('volume','rm',volume);state['cleanup']['volume_absent']=inspect('volume',volume,'{{.Name}}') is None
        else: state['cleanup']['volume_absent']=True
        if password_file.exists():
            if secret_dir.resolve()!=secret_dir or password_file.is_symlink(): raise RuntimeError('Refuse unowned credential cleanup')
            password_file.unlink()
        if secret_dir.exists():secret_dir.rmdir()
        state['cleanup']['password_directory_absent']=not secret_dir.exists()
        if not image_was_present and inspect('image',IMAGE,'{{.Id}}') is not None:
            refs=docker('ps','-a','--filter','ancestor='+IMAGE,'--format','{{.ID}}').stdout.strip()
            if not refs: docker('image','rm',IMAGE);state['cleanup']['new_image_reference_absent']=inspect('image',IMAGE,'{{.Id}}') is None
            else: state['cleanup']['image_retained_referenced']=True
        with socket.socket() as probe: state['cleanup']['port_closed']=probe.connect_ex(('127.0.0.1',33967))!=0
        if watcher is not None:
            watcher.wait(timeout=15);state['cleanup']['watchdog_exited']=watcher.returncode==0
        state['cleanup_at']=utc();state['phase']='cleaned';save()
    print(json.dumps({'receipt':str(record),'test_exit':state.get('test_exit'),'failure':state.get('failure'),'cleanup':state['cleanup']}))
    return result if not state.get('failure') else 1

if __name__=='__main__':
    if len(sys.argv)==3 and sys.argv[1]=='--watchdog': sys.exit(watchdog(sys.argv[2]))
    sys.exit(main())