"""Bounded private failure/recovery checks; synthetic input, sanitized aggregates only."""
import hashlib,json,shlex,subprocess,sys,time,urllib.request
from pathlib import Path
SHA=sys.argv[1]
assert len(SHA)==40 and all(c in '0123456789abcdef' for c in SHA)
INNER=r"""
import asyncio,importlib.util,json,sys,time
from pydantic import SecretStr
import httpx
from app.core.provenance.build import build_sha
from app.core.config import Settings
from app.domain.calculations.contracts import CalculationRequest,SelectedBirthInput
from app.domain.participants import ParticipantContext
from app.geo.providers import GeoNamesGeocoder
from app.geo.contracts import PlaceSearchRequest
from app.geo.ports import GeocoderError
from app.passport.client import APTClient
from app.services.passport_calculation import PassportCalculationService
from app.services.calculation_errors import CalculationError
d=json.load(sys.stdin);assert build_sha()==d['sha']
assert importlib.util.find_spec('swisseph') is None
case=d['case'];req=case['request'];p=req['selected_place']
selected=SelectedBirthInput.model_validate({'raw':{'date':req['civil']['date'],'time':req['civil']['time'],'place_query':p['query']},'selected_place':{'schema_version':'selected-place.v1','candidate':{k:p[k] for k in ('provider','source_id','display_name','latitude','longitude','attribution')},'search_request':{'query':p['query'],'limit':p['requested_limit']},'selected_index':p['selected_index'],'result_count':p['result_count']},'fold_choice':req['civil']['fold']})
request=CalculationRequest(person_a=selected,person_b=selected,context_a=ParticipantContext(),context_b=ParticipantContext())
revision='e0f25379079645a73d67c5f54c0e1290521083e0'
client=APTClient('https://apt.unbubble.cc',SecretStr(d['token']),revision,proxy='http://geonames-egress:3128')
mode=d['mode'];start=time.monotonic()
if mode=='invalid_auth':client._credential=SecretStr('apt1.'+'0'*16+'.'+'0'*64)
if mode=='timeout':
 async def slow(request):await asyncio.sleep(60)
 client._transport=httpx.MockTransport(slow)
if mode=='geonames_unavailable':
 provider=GeoNamesGeocoder(Settings(geonames_username=SecretStr('synthetic-not-a-credential'),geonames_proxy='http://geonames-egress:3128'))
 # Real proxy denies this unapproved hostname before any outside request; no provider secret sent.
 provider._url='https://blocked.example.invalid/searchJSON'
 try:asyncio.run(provider.search(PlaceSearchRequest(query='Sydney',limit=1)))
 except GeocoderError as error:category=error.kind.value
 else:raise SystemExit('Failure boundary did not reject')
 assert category in ('network','http')
else:
 service=PassportCalculationService(client,revision)
 try:result=service.calculate(request)
 except CalculationError as error:
  assert mode in ('invalid_auth','outage','timeout')
  category=error.category.value
  assert category==('timeout' if mode=='timeout' else 'unavailable')
  assert error.__context__ is None
 else:
  assert mode=='recovery' and result.manifest.content_sha256==(case['acep1_sha256'],case['acep1_sha256'])
  category='success'
elapsed=time.monotonic()-start
assert elapsed<13 and (mode!='timeout' or elapsed>=9.8)
print(json.dumps({'mode':mode,'category':category,'bounded_under_13_seconds':True,'seconds':round(elapsed,2),'no_local_science_installed':True,'no_fallback':True,'timeout_test':'injected silent transport; actual production deadline' if mode=='timeout' else None}))
"""
REMOTE=r"""
import json,subprocess,sys
from pathlib import Path
d=json.load(sys.stdin)
d['token']=json.loads(Path('/srv/astro-compatibility/env/apt-client.json').read_bytes())['token']
command=['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','--pids-limit','32','--tmpfs','/tmp:rw,noexec,nosuid,size=16m','ace-cutover-probe:'+d['sha'],'python','-c',d.pop('inner')]
p=subprocess.run(command,input=json.dumps(d).encode(),stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=45)
if p.returncode:raise SystemExit('Private failure probe failed; sensitive diagnostics withheld')
print(p.stdout.decode())
"""
case=json.loads(Path('/home/soul/astro-passport/tests/data/public-scientific-reference.v1.json').read_bytes())['cases'][0]
def probe(mode):
 p=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=10','ace-staging','python3 -c '+shlex.quote(REMOTE)],input=json.dumps({'sha':SHA,'case':case,'mode':mode,'inner':INNER}).encode(),stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=60)
 if p.returncode:raise RuntimeError('Private '+mode+' probe failed; diagnostics withheld')
 return json.loads(p.stdout)
def apt(cmd):return subprocess.check_output(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=10','apt',cmd],stderr=subprocess.PIPE).decode().strip()
reports=[probe('invalid_auth'),probe('timeout'),probe('geonames_unavailable')]
assert apt("docker inspect apt-hosted-app-1 --format '{{.Image}}'")=='sha256:887dead0e310af25cf73848b18259b1d758305acd10c653e53d0cc7b7402c14a'
assert apt("docker inspect apt-hosted-app-1 --format '{{.State.Running}}'")=='true'
apt('docker stop --time 10 apt-hosted-app-1')
try:reports.append(probe('outage'))
finally:apt('docker start apt-hosted-app-1')
for attempt in range(30):
 try:
  with urllib.request.urlopen('https://apt.unbubble.cc/health/ready',timeout=5) as response:
   if response.status==200:break
 except Exception:pass
 time.sleep(.5)
else:raise RuntimeError('APT failed recovery')
reports.append(probe('recovery'))
with urllib.request.urlopen('https://apt.unbubble.cc/source',timeout=10) as response:
 assert response.status==200
report={'ace_sha':SHA,'apt_sha':'e0f25379079645a73d67c5f54c0e1290521083e0','checks':reports,'apt_restarted_same_image':True,'anonymous_apt_source_available':True,'ace_process_recreated_each_probe':True,'public_ace_not_modified':True,'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-failures-'+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)
