"""Offline-only paired source-inventory proof for the existing CG opt-in method."""
import hashlib,importlib.util,json
from pathlib import Path
spec=importlib.util.spec_from_file_location('audit',Path(__file__).with_name('Audit-GalaxyClientCompatibility.py'))
audit=importlib.util.module_from_spec(spec);spec.loader.exec_module(audit)
old=audit.Image(Path('artifacts/ship-model-reference/client-copy/EliteDangerous64.exe'))
new=audit.Image(Path('D:/SteamLibrary/steamapps/common/Elite Dangerous/Products/elite-dangerous-odyssey-64/EliteDangerous64.exe'))
expected=('6891f70a021fa9f3a0e00458c284f48d1226e68ae7fc02ad48081aed47857e93','ed5a8f8cd10f9a80d3bda5badd7ba1d4fcfc15996c8c7e018852cb170e264b63')
assert tuple(hashlib.sha256(i.raw).hexdigest() for i in (old,new))==expected
after=0x3433030;fn=new.function(after);assert fn and fn[0]==after
reverse=audit.match(new,old,after,fn[1]-after)
dependencies=[];context=[];before=None
if reverse['status']=='ambiguous':
    # Distinguish the actual send primitive. Both bodies contain initiativeId,
    # but only one calls the independently unique corresponding HTTP helper.
    helper=0x9A5080;hfn=old.function(helper);assert hfn and hfn[0]==helper
    hmatch=audit.match(old,new,helper,hfn[1]-helper);assert hmatch['status']=='unique'
    helper_after=int(hmatch['newRva'],16);hmatch['oldRva']=hex(helper);dependencies.append(hmatch)
    candidates=[]
    for value in reverse['candidates']:
        candidate=int(value,16)
        bindings=[r for r in audit.references(old,new,candidate,after,fn[1]-after) if r[0]==helper and r[1]==helper_after]
        if len(bindings)==1:candidates.append((candidate,bindings[0]))
    if len(candidates)==1:
        before,binding=candidates[0]
        context.append(dict(oldFunction=hex(before),newFunction=hex(after),oldCall=hex(binding[3]),
            newCall=hex(after+binding[3]-before),oldCallee=hex(helper),newCallee=hex(helper_after)))
    # Original component constructor configures this exact typed request with
    # POST kind3 and optin endpoint; compare the complete paired constructor.
    ctor=0x1E87120;cfn=old.function(ctor);assert cfn and cfn[0]==ctor
    cmatch=audit.match(old,new,ctor,cfn[1]-ctor);assert cmatch['status']=='unique'
    ctor_after=int(cmatch['newRva'],16);cmatch['oldRva']=hex(ctor);dependencies.append(cmatch)
    cref=audit.references(old,new,ctor,ctor_after,cmatch['length'])
    assert any(a==0x5247D30 and b==0x5247D00 for a,b,_,_ in cref)
    assert any(a==0x511F9D0 and b==0x511F9D0 for a,b,_,_ in cref)
    endpoint=b'2.0/elite/initiative/optin\0'
    assert old.data(0x5247D30,len(endpoint))==new.data(0x5247D00,len(endpoint))==endpoint
if reverse['status']!='unique' and before is None:
    result=dict(runtimeNeutral=True,gameProcessAccess=False,gameCalls=0,canInstallHooks=False,runtimeValidated=False,
        oldImageSha256=expected[0],newImageSha256=expected[1],currentRva=hex(after),status='unresolved',reverseMatch=reverse,
        scope='No mapping published: full-body normalized match is ambiguous; no broader analysis performed')
    path=Path('artifacts/galaxy-client-compatibility/community-goal-optin-unresolved.json')
    path.write_text(json.dumps(result,indent=2)+'\n',encoding='utf8');print(json.dumps(result,indent=2));raise SystemExit(0)
if before is None:before=int(reverse['newRva'],16)
row=audit.match(old,new,before,fn[1]-after)
assert hex(after) in row['candidates']
if context:row.update(status='unique',newRva=hex(after),method='whole-body-and-independently-unique-call-target-with-typed-optin-constructor')
else:assert row['status']=='unique' and int(row['newRva'],16)==after
row['oldRva']=hex(before)
refs=audit.references(old,new,before,after,row['length'])
result=dict(runtimeNeutral=True,gameProcessAccess=False,gameCalls=0,networkRequests=0,canInstallHooks=False,runtimeValidated=False,
    oldImageSha256=expected[0],newImageSha256=expected[1],functions=[*dependencies,row],references=[list(map(hex,r)) for r in refs],
    callBindings=context,requestType=dict(oldVtable='0x511f9d0',newVtable='0x511f9d0',oldEndpoint='0x5247d30',newEndpoint='0x5247d00',endpoint='2.0/elite/initiative/optin',kind=3,
        oldKindInstruction='0x1e879c4',newKindInstruction=hex(ctor_after+0x1e879c4-ctor)),
    scope='Compatibility of an existing opt-in method only; no call, execution or semantic authorization is performed here')
path=Path('artifacts/galaxy-client-compatibility/community-goal-optin-compatibility.json')
path.write_text(json.dumps(result,indent=2)+'\n',encoding='utf8');print(json.dumps(result,indent=2))
