from pathlib import Path
from urllib.request import Request, urlopen
from datetime import datetime, timezone
from decimal import Decimal, getcontext
import json, hashlib
getcontext().prec=80
base=Path(__file__).resolve().parent/'captures'
base.mkdir(exist_ok=True)
url='https://api.exchange.coinbase.com/products/BTC-USD/book?level=2'
start=datetime.now(timezone.utc).isoformat()
with urlopen(Request(url,headers={'User-Agent':'DN-public-data-research/1.0','Accept':'application/json'}),timeout=30) as response:
    raw=response.read(5_000_001)
    if len(raw)>5_000_000: raise RuntimeError('Response exceeds bounded capture limit')
    status=response.status
    headers={k:response.headers.get(k) for k in ['Date','Content-Type','ETag','Age','Cache-Control'] if response.headers.get(k)}
finish=datetime.now(timezone.utc).isoformat()
data=json.loads(raw)
if not data.get('bids') or not data.get('asks'): raise RuntimeError('Empty book')
if data.get('auction_mode') is not False: raise RuntimeError('Explicit auction_mode=false is required; auction, missing, null or non-boolean mode cannot support the continuous-book method')
bid,ask=Decimal(data['bids'][0][0]),Decimal(data['asks'][0][0])
if bid>=ask: raise RuntimeError('Locked or crossed snapshot')
mid=(bid+ask)/2
bands=[]
for bps in [50,100,200]:
    result={'basis_points':bps,'midpoint':str(mid),'boundary':'inclusive'}
    for side in ['bids','asks']:
        rows=[x for x in data[side] if abs(Decimal(x[0])-mid)*10000<=mid*bps]
        result[side]={'included_levels':len(rows),'quote_notional':str(sum((Decimal(x[0])*Decimal(x[1]) for x in rows),Decimal(0)))}
    bands.append(result)
sample=next(({'side':side,'price':row[0],'aggregated_base_size':row[1],'order_count':row[2],'correct_quote_notional':str(Decimal(row[0])*Decimal(row[1])),'incorrect_if_multiplied_again':str(Decimal(row[0])*Decimal(row[1])*Decimal(row[2]))} for side in ['bids','asks'] for row in data[side] if int(row[2])>1),None)
receipt={'request_url':url,'requested_at_utc':start,'received_at_utc':finish,'http_status':status,'response_headers':headers,'raw_bytes':len(raw),'sha256':hashlib.sha256(raw).hexdigest(),'authentication':'None; public read-only request','sequence':str(data.get('sequence')),'provider_time':data.get('time'),'auction_mode':data.get('auction_mode'),'rows_per_side':{k:len(data[k]) for k in ['bids','asks']},'scope':'One historical Level 2 response, not a continuously reconciled book or execution result'}
(base/'coinbase-btc-usd-level2.raw.json').write_bytes(raw)
(base/'receipt.json').write_text(json.dumps(receipt,indent=2)+'\n')
(base/'depth-analysis.json').write_text(json.dumps({'receipt':receipt,'bands':bands,'aggregated_size_example':sample,'method':'Sum price times aggregated base size at levels within an inclusive midpoint-relative band. Do not multiply by the order count. No fees, fills, cancellations or cross-venue aggregation are measured.'},indent=2)+'\n')
print(json.dumps({'receipt':receipt,'bands':bands,'aggregated_size_example':sample},indent=2))
