#!/usr/bin/env python3
"""ApexLiqRadar Zero-Dependency Multicall3 Borrower Health Poller."""
import json, sys, time, urllib.request

DEMO_URL = "https://apexliqradar.com/sample_25_krill.json"
MC3 = "0xcA11bde05977b3631167028862bE2a173976CA11"
RPCS = {
    "base": "https://mainnet.base.org", "arbitrum": "https://arb1.arbitrum.io/rpc",
    "optimism": "https://mainnet.optimism.io", "polygon": "https://polygon-bor-rpc.publicnode.com",
    "scroll": "https://rpc.scroll.io", "linea": "https://rpc.linea.build",
    "gnosis": "https://rpc.gnosischain.com", "avalanche": "https://api.avax.network/ext/bc/C/rpc",
    "bnb": "https://bsc-dataseed.binance.org", "ethereum": "https://ethereum-rpc.publicnode.com",
}

def load_targets():
    if len(sys.argv) > 1:
        doc = json.loads(open(sys.argv[1], encoding='utf-8').read())
    else:
        req = urllib.request.Request(DEMO_URL, headers={'User-Agent': 'apex-starter-poller/1.0'})
        doc = json.loads(urllib.request.urlopen(req, timeout=8).read().decode('utf-8'))
    return doc.get('wallets') or doc.get('positions') or doc

def encode_mc3(rows):
    n = len(rows)
    head = '0x82ad56cb' + f'{32:064x}' + f'{n:064x}'
    offs = ''.join(f'{n * 32 + i * 160:064x}' for i in range(n))
    els = []
    for r in rows:
        pool = r['pool_contract_address'][2:].lower().zfill(64)
        usr = r['borrower_address'][2:].lower().zfill(64)
        cd = 'bf92857c' + usr
        els.append(pool + f'{1:064x}' + f'{96:064x}' + f'{36:064x}' + cd + ('0' * 56))
    return head + offs + ''.join(els)

def poll_once(rows):
    by_chain = {}
    for r in rows:
        if r.get('pool_contract_address') and r.get('borrower_address'):
            by_chain.setdefault(r['chain'], []).append(r)
    for chain, batch in by_chain.items():
        rpc = RPCS.get(chain)
        if not rpc: continue
        body = json.dumps({'jsonrpc':'2.0','id':1,'method':'eth_call','params':[{'to':MC3,'data':encode_mc3(batch[:40])},'latest']}).encode()
        req = urllib.request.Request(rpc, data=body, headers={'Content-Type':'application/json'})
        raw_hex = json.loads(urllib.request.urlopen(req, timeout=8).read().decode()).get('result', '')[2:]
        if len(raw_hex) < 128: continue
        base_p = 128
        for i, r in enumerate(batch[:40]):
            el_off = base_p + int(raw_hex[base_p + i*64 : base_p + (i+1)*64], 16) * 2
            ok = int(raw_hex[el_off : el_off + 64], 16)
            d_len = int(raw_hex[el_off + 128 : el_off + 192], 16)
            ret = raw_hex[el_off + 192 : el_off + 192 + d_len * 2]
            if ok == 1 and len(ret) >= 384:
                col = int(ret[0:64], 16) / 1e8; dbt = int(ret[64:128], 16) / 1e8; hf = int(ret[320:384], 16) / 1e18
                if dbt > 0: print(f'[{chain.upper()}] {r["borrower_address"]} | Col=${col:,.2f} | Debt=${dbt:,.2f} | HF={hf:.4f}')

if __name__ == '__main__':
    targets = load_targets()
    print(f'Loaded {len(targets)} active targets from ApexLiqRadar. Polling live Multicall3...')
    poll_once(targets)
