"""Read-only Lido/wstETH/Aave claim graph. Standard-library Python; no wallet.

Usage: python capture_public.py OUTPUT_DIR [BLOCK_NUMBER_OR_HEX]
Without a block, pin the endpoint's finalized block. All eth_call use that number,
and its hash is checked again after the calls. An archive-capable RPC may be
needed to repeat a historical capture. This is not a consensus-state proof.
"""
import concurrent.futures
import datetime as dt
import hashlib
import json
import sys
import urllib.request
from pathlib import Path

RPC = 'https://ethereum-rpc.publicnode.com'
STETH = '0xae7ab96520de3a18e5e111b5eaab095312d7fe84'
WSTETH = '0x7f39c581f595b53c5cb19bd0b3f8da6c935e2ca0'
ATOKEN = '0x0b925ed163218f6662a35e0f0371ac234f9e9371'
WAD = 10 ** 18
SELECTORS = {'totalSupply()':'18160ddd','balanceOf(address)':'70a08231','decimals()':'313ce567','getTotalPooledEther()':'37cfdaca','getTotalShares()':'d5002f2e','getExternalEther()':'e16a9065','getExternalShares()':'63021d8b','getStETHByWstETH(uint256)':'bb2952fc','stEthPerToken()':'035faf82','stETH()':'c1fe3e48','UNDERLYING_ASSET_ADDRESS()':'b16a19de'}

def utc():
    return dt.datetime.now(dt.timezone.utc).isoformat()

def call(method, params):
    request = {'jsonrpc':'2.0','id':1,'method':method,'params':params}
    started = utc()
    with urllib.request.urlopen(urllib.request.Request(RPC, data=json.dumps(request).encode(), headers={'Content-Type':'application/json','User-Agent':'DN-Research/1.0'}), timeout=25) as response:
        raw = response.read()
        status = response.status
    result = json.loads(raw)
    if status != 200 or 'error' in result or 'result' not in result:
        raise ValueError({'request':request,'status':status,'response':result})
    return {'request':request,'response':result,'http_status':status,'request_started_at_utc':started,'response_received_at_utc':utc(),'response_sha256':hashlib.sha256(raw).hexdigest()}

def text_units(n):
    q, r = divmod(n, WAD)
    return str(q) + ('.' + str(r).zfill(18).rstrip('0') if r else '')

def main():
    out = Path(sys.argv[1]); out.mkdir(parents=True, exist_ok=True)
    chain = call('eth_chainId', [])
    if int(chain['response']['result'], 16) != 1: raise ValueError('Ethereum mainnet required')
    requested = hex(int(sys.argv[2],0)) if len(sys.argv)>2 else 'finalized'
    block = call('eth_getBlockByNumber', [requested,False]); b = block['response']['result']
    if not b or not b.get('hash'): raise ValueError('Pinned block unavailable')
    pin = b['number']
    def read(job):
        label, address, signature, argument = job
        encoded = '' if argument is None else (argument[2:].rjust(64,'0') if isinstance(argument,str) else hex(argument)[2:].rjust(64,'0'))
        r = call('eth_call',[{'to':address,'data':'0x'+SELECTORS[signature]+encoded},pin]); raw = r['response']['result']
        if not isinstance(raw,str) or len(raw)!=66: raise ValueError(label+': expected one ABI word')
        r.update(label=label,signature=signature,decoded_integer=str(int(raw,16)))
        return label,r
    jobs = [('lido_reported_pooled_eth',STETH,'getTotalPooledEther()',None),('steth_total_supply',STETH,'totalSupply()',None),('steth_total_shares',STETH,'getTotalShares()',None),('steth_external_ether',STETH,'getExternalEther()',None),('steth_external_shares',STETH,'getExternalShares()',None),('wrapper_steth_balance',STETH,'balanceOf(address)',WSTETH),('wsteth_total_supply',WSTETH,'totalSupply()',None),('aave_physical_wsteth',WSTETH,'balanceOf(address)',ATOKEN),('aave_atoken_total_supply',ATOKEN,'totalSupply()',None),('wsteth_to_steth_one',WSTETH,'stEthPerToken()',None),('wrapper_underlying',WSTETH,'stETH()',None),('aave_underlying',ATOKEN,'UNDERLYING_ASSET_ADDRESS()',None),('steth_decimals',STETH,'decimals()',None),('wsteth_decimals',WSTETH,'decimals()',None),('atoken_decimals',ATOKEN,'decimals()',None)]
    with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: calls=dict(pool.map(read,jobs))
    val=lambda key:int(calls[key]['decoded_integer'])
    if val('wrapper_underlying') != int(STETH,16) or val('aave_underlying') != int(WSTETH,16): raise ValueError('Underlying identity mismatch')
    if any(val(k)!=18 for k in ['steth_decimals','wsteth_decimals','atoken_decimals']): raise ValueError('Unexpected decimals')
    jobs=[('all_wsteth_claim_steth',WSTETH,'getStETHByWstETH(uint256)',val('wsteth_total_supply')),('aave_physical_claim_steth',WSTETH,'getStETHByWstETH(uint256)',val('aave_physical_wsteth'))]
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: calls.update(dict(pool.map(read,jobs)))
    after=call('eth_getBlockByNumber',[pin,False])
    if after['response']['result']['hash'] != b['hash']: raise ValueError('Pinned block hash changed')
    R=val('steth_total_supply'); B=val('all_wsteth_claim_steth'); C=val('aave_physical_claim_steth')
    if not 0<=C<=B<=R: raise ValueError('Observed nested quantities are inconsistent')
    if R != val('lido_reported_pooled_eth'): raise ValueError('Reported pooled ether differs from token supply')
    if val('wrapper_steth_balance') < B: raise ValueError('Wrapper custody is below the declared stETH claim')
    if val('aave_physical_wsteth') > val('wsteth_total_supply'): raise ValueError('Custody exceeds receipt supply')
    raw={'rpc':RPC,'capture_completed_at_utc':utc(),'chain':chain,'block':block,'block_recheck':after,'addresses':{'steth':STETH,'wsteth':WSTETH,'aave_wsteth_atoken':ATOKEN},'calls':calls}
    analysis={'chain_id':1,'block_number':int(pin,16),'block_hash':b['hash'],'block_timestamp_utc':dt.datetime.fromtimestamp(int(b['timestamp'],16),dt.timezone.utc).isoformat(),'capture_completed_at_utc':raw['capture_completed_at_utc'],
        'unit':'stETH accounting units after onchain wstETH conversion; not spot ETH or USD market value',
        'R_reported_root_supply':text_units(R),'B_all_wrapped_claims':text_units(B),'C_aave_physical_custody_lookthrough':text_units(C),
        'candidate_gross_layer_sum':text_units(R+B+C),'nested_overlap_subtraction':text_units(B+C),'conditional_distinct_root_exposure':text_units(R),
        'wrapper_steth_custody':text_units(val('wrapper_steth_balance')),'wrapper_custody_minus_total_claim_raw_units':str(val('wrapper_steth_balance')-B),
        'wsteth_supply':text_units(val('wsteth_total_supply')),'aave_physical_wsteth':text_units(val('aave_physical_wsteth')),'aave_atoken_total_supply_wsteth':text_units(val('aave_atoken_total_supply')),
        'one_wsteth_in_steth':text_units(val('wsteth_to_steth_one')),
        'conversion_basis':'Exact getStETHByWstETH result; cross-check uses internal ether / internal shares, not rounded total pooled ether / total shares',
        'conversion_check_total_claim':str(val('wsteth_total_supply')*(R-val('steth_external_ether'))//(val('steth_total_shares')-val('steth_external_shares')))==str(B),
        'conversion_check_aave_claim':str(val('aave_physical_wsteth')*(R-val('steth_external_ether'))//(val('steth_total_shares')-val('steth_external_shares')))==str(C),
        'assumptions':['Rows are nested accounting representations, not three independent stocks.','Root quantity is protocol-reported pooled ether / stETH supply, not independent validator-balance verification.','C is only wstETH physically held at the selected Aave aToken address; supplier claims and debt are different quantities.','The candidate gross sum is an educational roll-up, not a reported DefiLlama total.','No spot-price parity, immediate redemption, solvency, beneficial-owner mapping or global unique-capital conclusion.']}
    (out/'snapshot_raw.json').write_text(json.dumps(raw,indent=2)+'\n')
    (out/'snapshot_analysis.json').write_text(json.dumps(analysis,indent=2)+'\n')
    print(json.dumps(analysis,indent=2))

if __name__=='__main__': main()
