"""Private operator-only form rehearsal; no published listener, no secret output."""
import hashlib
import json
import os
import stat
import subprocess
import sys
from pathlib import Path

ROOT=Path('/home/soul/astrological-compatibility-engine')
SHA=sys.argv[1]
assert len(SHA)==40 and all(c in '0123456789abcdef' for c in SHA)
secret=Path('/home/soul/ace-geonames.env')
assert stat.S_IMODE(secret.stat().st_mode)==0o600
username=next(x.partition('=')[2].strip().strip(chr(34)+chr(39)) for x in secret.read_text().splitlines() if x.startswith('ACE_GEONAMES_USERNAME='))
INNER=r"""
import asyncio,base64,json,secrets,sys
from datetime import UTC,datetime,timedelta
from html.parser import HTMLParser
from pydantic import SecretStr
import httpx
from app.api.application import create_app
from app.core.config import Settings
from app.core.provenance.build import build_sha
from app.geo.providers import GeoNamesGeocoder
from app.passport.client import APTClient
from app.services.passport_calculation import PassportCalculationService
from app.services.calculation_worker import CalculationWorker
from app.services.place_selection import PlaceSelectionService
from app.vs04.runtime import TesterRuntime
from app.vs04.state import TesterState
data=json.load(sys.stdin)
assert build_sha()==data['sha']
def forbidden(*args,**kwargs):raise RuntimeError('Local scientific production forbidden in private rehearsal')
for name,attribute in [('app.ephemeris.swiss.adapter','SwissEphemeris'),('app.timezone.boundaries.tbb','TBBTimezoneBoundaryResolver'),('app.timezone.resolution.tzdb','PinnedCivilTimeResolver')]:
 if name in sys.modules:
  cls=getattr(sys.modules[name],attribute)
  for method in ('calculate','resolve'):
   if hasattr(cls,method):setattr(cls,method,forbidden)
revision='e0f25379079645a73d67c5f54c0e1290521083e0'
access=secrets.token_hex(32)
config=dict(environment='production',public_url='https://operator.invalid',secret_key=SecretStr(secrets.token_hex(32)),database_url=SecretStr('postgresql+psycopg://unused:unused@not-connected/unused?sslmode=verify-full'),geonames_username=SecretStr(data['username']),geonames_proxy='http://geonames-egress:3128',vs04_enabled=True,vs04_access_secret=SecretStr(access),vs04_expires_at=datetime.now(UTC)+timedelta(hours=1))
if 'apt_base_url' in Settings.model_fields:
 config.update(apt_base_url='https://apt.unbubble.cc',apt_api_key=SecretStr(data['token']),apt_source_revision=revision,apt_proxy='http://geonames-egress:3128')
settings=Settings(**config)
class Parser(HTMLParser):
 def __init__(self,html):
  super().__init__();self.values={};self.feed(html)
 def handle_starttag(self,tag,attrs):
  a=dict(attrs)
  if tag=='input' and a.get('name') and (a.get('type')!='radio' or 'checked' in a):self.values[a['name']]=a.get('value','')
  if tag=='select' and a.get('name'):self.values[a['name']]=''
class ReceiptSource:
 def __init__(self):
  self.client=APTClient('https://apt.unbubble.cc',SecretStr(data['token']),revision,proxy='http://geonames-egress:3128');self.receipts=[]
 async def create(self,selected):
  receipt=await self.client.create(selected);self.receipts.append(receipt);return receipt
async def main():
 source=ReceiptSource()
 app=create_app(settings)
 # The entire real form/middleware/lifespan is exercised privately in this isolated image.
 async with app.router.lifespan_context(app):
  runtime=app.state.vs04_runtime
  source.client=runtime.worker._service._source
  runtime.worker._service._source=source
  async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app),base_url='https://operator.invalid',headers={'Authorization':'Basic '+base64.b64encode(('tester:'+access).encode()).decode()}) as c:
   assert (await c.get('/vs04',headers={'Authorization':'invalid'})).status_code==401
   r=await c.get('/vs04');assert r.status_code==200
   values=Parser(r.text).values
   for person,query,date in [('a','Saint Petersburg','1976-07-14'),('b','Sydney','1985-07-14')]:
    values.update({person+'_query':query,person+'_date':date,person+'_time':'12:34:56', 'action':'search-'+person})
    r=await c.post('/vs04',data=values,headers={'Origin':'https://operator.invalid'})
    if r.status_code!=200:
     from app.geo.ports import GeocoderFailure
     print('Private rehearsal failed: search status '+str(r.status_code)+' category '+next((k.value for k in GeocoderFailure if ': '+k.value+'.' in r.text),'form'),file=sys.stderr);sys.exit(1)
    assert 'value="0"' in r.text, 'search/selection failed'
    values=Parser(r.text).values;values[person+'_choice']='0'
   values['action']='calculate'
   bad=await c.post('/vs04',data=values|{'a_choice':'9'},headers={'Origin':'https://operator.invalid'})
   assert bad.status_code==400 and not source.receipts
   r=await c.post('/vs04',data=values,headers={'Origin':'https://operator.invalid'})
   assert r.status_code==200 and 'calculation-manifest.v2' in r.text and len(source.receipts)==2,'calculation failed'
   assert 'A sun ↔ B moon' in r.text and 'A moon ↔ B sun' in r.text
   assert r.headers['cache-control']=='no-store'
   assert all(s not in r.text for s in (data['token'],data['username'],access))
   assert not any(n in sys.modules for n in ('swisseph','shapely','numpy'))
   assert 'not_sent_ais_contract_pending' in r.text
   report={'ace_revision':data['sha'],'apt_revision':revision,'form_origin':'operator-only ASGI in non-root isolated container; no listener','live_geonames_searches':2,'explicit_selections':2,'remote_apt_receipts':2,'manifest':'calculation-manifest.v2','cross_chart_pairs':4,'invalid_selection_rejected_before_apt':True,'authentication_required':True,'no_store':True,'native_science_not_loaded':True,'production_startup_used':True,'ais_preparation_not_sent':True,'public_ace_untouched':True,'raw_inputs_persisted':False}
 print(json.dumps(report))
try:asyncio.run(main())
except Exception as e:
 import traceback
 print('Private rehearsal failed: '+type(e).__name__+' line '+str(traceback.extract_tb(e.__traceback__)[-1].lineno),file=sys.stderr);sys.exit(1)
"""
REMOTE=r"""
import json,subprocess,sys,os
from pathlib import Path
d=json.load(sys.stdin)
def run(args):return subprocess.run(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE,check=True)
root=Path('/srv/astro-compatibility/cp007r');root.mkdir(mode=0o700,exist_ok=True)
conf=root/'squid.conf';conf.write_text(d['squid']);conf.chmod(0o644)
secret=root/'geonames.env'
fd=os.open(secret,os.O_WRONLY|os.O_CREAT|os.O_TRUNC,0o600)
with os.fdopen(fd,'w') as f:f.write('ACE_GEONAMES_USERNAME='+d['username']+'\n')
for network,internal in [('ace-cp007r-provider',True),('ace-cp007r-egress',False)]:
 if subprocess.run(['docker','network','inspect',network],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL).returncode:
  run(['docker','network','create']+(['--internal','--opt','com.docker.network.bridge.gateway_mode_ipv4=isolated'] if internal else [])+[network])
proxy='ace-cp007r-egress'
if subprocess.run(['docker','container','inspect',proxy],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL).returncode:
 run(['docker','create','--name',proxy,'--network','ace-cp007r-provider','--network-alias','geonames-egress','--user','10001:10001','--read-only','--cap-drop','ALL','--security-opt','no-new-privileges','--memory','128m','--pids-limit','32','--tmpfs','/tmp:rw,noexec,nosuid,size=16m','--mount','type=bind,src='+str(conf)+',dst=/etc/squid/squid.conf,readonly','--entrypoint','/usr/sbin/squid-gnutls',d['proxy_image'],'-N','-f','/etc/squid/squid.conf'])
 run(['docker','network','connect','ace-cp007r-egress',proxy]);run(['docker','start',proxy])
token=json.loads(Path('/srv/astro-compatibility/env/apt-client.json').read_bytes())['token']
image='ace-cutover-probe:'+d['sha']
cmd=['docker','run','--rm','-i','--network','ace-cp007r-provider','--dns','127.0.0.1','--no-healthcheck','--log-driver','none','--read-only','--cap-drop','ALL','--security-opt','no-new-privileges','--ulimit','core=0','--memory','256m','--memory-swap','256m','--pids-limit','32','--tmpfs','/tmp:rw,noexec,nosuid,size=16m',image,'python','-c',d['inner']]
p=subprocess.run(cmd,input=json.dumps({'sha':d['sha'],'username':d['username'],'token':token}).encode(),stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=120)
if p.returncode:
 print(json.dumps({'failure':'candidate','diagnostic':p.stderr.decode().splitlines()[-1] if p.stderr.startswith(b'Private rehearsal failed: ') else 'startup failure'}));sys.exit(1)
report=json.loads(p.stdout)
report['image']=run(['docker','image','inspect','--format','{{.Id}}',image]).stdout.decode().strip()
print(json.dumps(report))
"""
squid=(ROOT/'deploy/staging/egress/squid.conf').read_text().replace('acl only_geonames dstdomain -n secure.geonames.org','acl only_geonames dstdomain -n secure.geonames.org apt.unbubble.cc')
payload={'sha':SHA,'username':username,'inner':INNER,'squid':squid,'proxy_image':'ubuntu/squid:7.2-26.04_edge@sha256:c273042bd5f7e289ff50afa82079f4f2e36ce5172cc85321d2cb6f18b6ca2fe6'}
p=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=10','ace-staging','python3 -c '+__import__('shlex').quote(REMOTE)],input=json.dumps(payload).encode(),stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=200)
if p.returncode:
 print('Remote failure category:', 'setup' if b'Traceback' in p.stderr else 'candidate')
 if p.stdout.startswith(b'{'):
  failure=json.loads(p.stdout);print(failure.get('diagnostic','withheld'))
 raise SystemExit('Private candidate failed; sensitive output suppressed')
report=json.loads(p.stdout);report['operator_tool_sha256']=hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
body=json.dumps(report,indent=2)+'\n'
target=Path('/home/soul/apt-cutover-ops/evidence')/('cp007r-production-rehearsal-'+SHA[:7]+'.json')
assert not target.exists()
subprocess.run(['apply_patch'],input='*** Begin Patch\n*** Add File: '+str(target)+'\n'+''.join('+'+x+'\n' for x in body.splitlines())+'*** End Patch\n',text=True,check=True)
print(body)
