"""Private ephemeral ACE image -> actual protected APT; no listener or staging switch."""
import json,subprocess,hashlib
from pathlib import Path
ROOT=Path(__file__).resolve().parent
SHA=__import__('sys').argv[1]
corpus_raw=Path('/home/soul/astro-passport/tests/data/public-scientific-reference.v1.json').read_bytes()
corpus_sha=hashlib.sha256(corpus_raw).hexdigest()
assert corpus_sha=='00b09dbebcc61bc4ae4a3d28c3ebb2b19af66f58c0406caef8a0b5a66013a826'
script_sha=hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
corpus=json.loads(corpus_raw)
INNER=r"""
import json,sys,hashlib
from pydantic import SecretStr
from app.core.provenance.build import build_sha
from app.domain.calculations.contracts import CalculationRequest,SelectedBirthInput
from app.domain.participants import ParticipantContext
from app.passport.client import APTClient
from app.services.calculation_errors import CalculationError
from app.services.passport_calculation import PassportCalculationService
data=json.load(sys.stdin)
assert build_sha()==data['sha']
assert not any(n.startswith(('swisseph','shapely','numpy','app.ephemeris.swiss','app.timezone.boundaries.tbb','app.timezone.resolution.tzdb')) for n in sys.modules)
revision='e0f25379079645a73d67c5f54c0e1290521083e0'
client=APTClient('https://apt.unbubble.cc',SecretStr(data['token']),revision)
service=PassportCalculationService(client,revision)
success=failures=0
for case in data['corpus']['cases']:
    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())
    try:result=service.calculate(request)
    except CalculationError as error:
        assert 'error' in case
        expected={'civil_ambiguous':'ambiguous_local_time','civil_nonexistent':'nonexistent_local_time','invalid_fold':'invalid_fold','boundary_boundary':'unresolved_geography','boundary_ambiguous':'unresolved_geography','boundary_no_match':'unresolved_geography'}[case['error']['code']]
        assert error.category.value==expected and error.person=='A'
        failures+=1;continue
    assert 'expected' in case
    assert result.manifest.content_sha256==(case['acep1_sha256'],case['acep1_sha256'])
    assert result.manifest.ace_git_sha==data['sha'] and result.manifest.apt_source_revision==revision
    assert result.manifest.schema_version=='calculation-manifest.v2'
    for position,expected in zip(result.payload.person_a.natal.astronomy.positions,case['expected']['bodies'],strict=True):
        assert position.binary64_hex==expected['binary64_hex'] and format(position.longitude,'.9f')==expected['decimal_degrees']
    assert len(result.payload.synastry.pairs)==4
    assert result.payload.synastry.pairs[0].separation_e9==0 and result.payload.synastry.pairs[3].separation_e9==0
    assert result.payload.synastry.pairs[1].separation_e9==result.payload.synastry.pairs[2].separation_e9
    success+=1
assert success==13 and failures==10
print(json.dumps({'schema':'ace-apt-private-consumer-probe.v1','ace_revision':data['sha'],'apt_revision':revision,'cases':23,'successes':success,'classified_failures':failures,'scientific_mismatches':0,'canonical_digest_mismatches':0,'private_four_pair_geometry':True,'v2_source_provenance':True,'no_local_scientific_producer_import':True,'listener_exposed':False,'staging_primary_changed':False,'credential_exported_from_host':False}))
"""
REMOTE=r"""
import json,subprocess,hashlib
from pathlib import Path
sha=SHA
secret=json.loads(Path('/srv/astro-compatibility/env/apt-client.json').read_bytes())
payload={'sha':sha,'token':secret['token'],'corpus':CORPUS}
image='ace-cutover-probe:'+sha
identity=subprocess.check_output(['docker','image','inspect','--format','{{.Id}}',image],text=True).strip()
command=['docker','run','--rm','-i','--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','--cpus','1','--tmpfs','/tmp:rw,noexec,nosuid,size=16m',image,'python','-c',INNER]
result=subprocess.run(command,input=json.dumps(payload).encode(),stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=600)
if result.returncode:raise SystemExit('Private consumer probe failed; sensitive diagnostics suppressed')
report=json.loads(result.stdout);report['ace_image']=identity
print(json.dumps(report))
"""
remote=REMOTE.replace('sha=SHA','sha='+repr(SHA)).replace('corpus\':CORPUS','corpus\':'+repr(corpus)).replace("'corpus':CORPUS","'corpus':"+repr(corpus)).replace("image,'python','-c',INNER","image,'python','-c',"+repr(INNER))
result=subprocess.run(['ssh','-o','BatchMode=yes','-o','StrictHostKeyChecking=yes','ace-staging','python3 -'],input=remote.encode(),stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=660)
if result.returncode:raise SystemExit('Remote private consumer probe failed; no sensitive diagnostics printed')
report=json.loads(result.stdout)
assert hashlib.sha256(Path(__file__).read_bytes()).hexdigest()==script_sha
report['probe_script_sha256']=script_sha
report['public_corpus_sha256']=corpus_sha
body=json.dumps(report,indent=2)+'\n'
target=ROOT/('evidence/cp007r-consumer-'+SHA[:7]+'.json')
assert not target.exists()
patch='*** Begin Patch\n*** Add File: '+str(target)+'\n'+''.join('+'+line+'\n' for line in body.splitlines())+'*** End Patch\n'
subprocess.run(['apply_patch'],input=patch,text=True,check=True)
print(body)
