"""Recompute DN depth bands from the saved public Coinbase snapshot; no network."""
from pathlib import Path
from decimal import Decimal, getcontext
import argparse, gzip, hashlib, json

getcontext().prec = 80
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('snapshot', nargs='?', default=str(Path(__file__).with_name('coinbase-btc-usd-level2.raw.json.gz')))
args = parser.parse_args()
path = Path(args.snapshot)
stored = path.read_bytes()
raw = gzip.decompress(stored) if path.suffix == ".gz" else stored
book = json.loads(raw)
if book.get('auction_mode') is not False:
    raise ValueError('Explicit non-auction mode is required for this reproduction.')
for side in ['bids', 'asks']:
    if not book.get(side): raise ValueError('Both sides must be present.')
    prices = [Decimal(row[0]) for row in book[side]]
    if len(set(prices)) != len(prices): raise ValueError('Duplicate aggregated price level.')
    if prices != sorted(prices, reverse=side == 'bids'): raise ValueError('Book prices are not ordered.')
    if any(Decimal(row[0]) <= 0 or Decimal(row[1]) <= 0 for row in book[side]):
        raise ValueError('Snapshot prices and displayed sizes must be positive.')
bid, ask = Decimal(book['bids'][0][0]), Decimal(book['asks'][0][0])
if bid >= ask: raise ValueError('Locked/crossed continuous book is unsupported.')
midpoint = (bid + ask) / 2
bands = []
for bps in [50, 100, 200]:
    band = {'basis_points': bps, 'midpoint': str(midpoint), 'boundary': 'inclusive'}
    for side in ['bids', 'asks']:
        included = [row for row in book[side] if abs(Decimal(row[0]) - midpoint) * 10000 <= midpoint * bps]
        band[side] = {'included_levels': len(included), 'quote_notional': str(sum((Decimal(row[0]) * Decimal(row[1]) for row in included), Decimal(0)))}
    bands.append(band)
result = {
    'sha256': hashlib.sha256(raw).hexdigest(),
    'raw_bytes': len(raw), 'sequence': str(book['sequence']),
    'provider_time': book.get('time'), 'auction_mode': book['auction_mode'],
    'rows_per_side': {side: len(book[side]) for side in ['bids', 'asks']},
    'bands': bands,
    'ring_1pct_to_2pct': {side: str(Decimal(bands[2][side]['quote_notional']) - Decimal(bands[1][side]['quote_notional'])) for side in ['bids', 'asks']},
    'scope': 'Offline arithmetic on saved returned levels; no execution, continuity or completeness audit.'
}
print(json.dumps(result, indent=2))
