"""Offline Decimal audit of public original material and separately archived later queries.
No network, no mutation of original inputs. Cap equality is a reference comparison,
not a historical policy binding unless separately supported by a dated rule.
"""
from pathlib import Path
from decimal import Decimal as D
from collections import Counter
import json,datetime as dt,hashlib,gzip,base64,zipfile,io,csv
ROOT=Path(__file__).resolve().parent; ORIG=Path('original')
ARCH=json.loads(gzip.decompress((ROOT/'2026-10-24-cap-review-inputs.json.gz').read_bytes()))
def read(p):return json.loads(ARCH['originalPublicJsonText'][p.name],parse_float=D)
def iso(t):return dt.datetime.fromtimestamp(t/1000,dt.timezone.utc).isoformat(timespec='milliseconds').replace('+00:00','Z')
def ms(t):return int(dt.datetime.fromisoformat(t.replace('Z','+00:00')).timestamp()*1000)
def median(a):
 s=sorted(a);n=len(s);return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2

def quant(a,p):
 s=sorted(a);pos=D(len(s)-1)*p;lo=int(pos);return s[lo]+(s[min(lo+1,len(s)-1)]-s[lo])*(pos-lo)
def rows(label,sym):
 out=[]
 for name,x in sorted(ARCH['laterQueries']['cap-history-requery'].items()):
  if not name.startswith(label+'-'+sym+'-'):continue
  assert hashlib.sha256(x['body'].encode()).hexdigest()==x['bodySha256'];out.extend(json.loads(x['body']))
 assert len(out)==len({r['fundingTime'] for r in out});return out
old=read(ORIG/'_fcap_years_0820.json')['results'];panel=[];year_differences=[]
for sym,o in old.items():
 if 'error' in o:continue
 rr=rows('panel',sym);v=[D(r['fundingRate']) for r in rr];c=D(str(o['cap_today'])) if o['cap_today'] is not None else None;f=D(str(o['floor_today'])) if o['floor_today'] is not None else None
 years=[]
 for year in sorted({iso(r['fundingTime'])[:4] for r in rr}):
  yy=[r for r in rr if iso(r['fundingTime']).startswith(year)];vv=[D(r['fundingRate']) for r in yy]
  y={'year':year,'n':len(vv),'max':max(vv),'min':min(vv),'negative':sum(z<0 for z in vv),'aboveAnchor':sum(z>D('.0001') for z in vv),'aboveAnchorPercent':D(sum(z>D('.0001') for z in vv))*100/len(vv),'negativePercent':D(sum(z<0 for z in vv))*100/len(vv),'median':median(vv),'interpolatedQ1':quant(vv,D('.25')),'interpolatedQ3':quant(vv,D('.75')),'oldRankQ1':sorted(vv)[len(vv)//4],'oldRankQ3':sorted(vv)[3*len(vv)//4]}
  oy=o['years'][year]
  for key,oldkey in [('n','n'),('max','max'),('min','min'),('aboveAnchor','above_anchor')]:
   if y[key]!=oy[oldkey]:year_differences.append({'symbol':sym,'year':year,'field':key,'new':y[key],'old':oy[oldkey]})
  assert abs(y['negativePercent']-D(str(oy['negative_pct'])))<D('1e-12')
  years.append(y)
 vmax,vmin=max(v),min(v)
 panel.append({'symbol':sym,'board':o['board'],'n':len(rr),'first':iso(rr[0]['fundingTime']),'last':iso(rr[-1]['fundingTime']),'max':max(v),'min':min(v),'referenceCap':c,'referenceFloor':f,'maxAsPercentOfReferenceCap':max(v)/c*100 if c is not None else None,'minAsPercentOfReferenceFloor':min(v)/f*100 if f is not None else None,'maxAt':[iso(r['fundingTime']) for r in rr if D(r['fundingRate'])==vmax],'minAt':[iso(r['fundingTime']) for r in rr if D(r['fundingRate'])==vmin],'equalReferenceCap':sum(z==c for z in v) if c is not None else None,'equalReferenceFloor':sum(z==f for z in v) if f is not None else None,'above30PercentOfReferenceCap':sum(z>c*D('.3') for z in v) if c is not None else None,'above50PercentOfReferenceCap':sum(z>c*D('.5') for z in v) if c is not None else None,'years':years})
assert not year_differences,year_differences
btc=next(x for x in panel if x['symbol']=='BTCUSDT');original_btc=dict(read(ORIG/'_fcap_btc_series_0820.json'));assert original_btc=={r['fundingTime']:D(r['fundingRate']) for r in rows('panel','BTCUSDT')}
# A 24-point reconstruction from 23 archived completed rows and the separately
# preserved corrected final hour is a reconstruction, not the missing final envelope.
a=read(ORIG/'_fcap_deep_0820_athenum.json');f=read(ORIG/'_fcap_feed_final_0820.json');w=[r for r in a['https://api.athenum.xyz/api/v1/futures/overview/metrics?asset=BTC']['data']['data'] if f['window_from']<=r['time']<=f['window_to']];assert len(w)==24 and len({r['time'] for r in w})==24
fund=[]
for venue,expected in f['per_8h_pct'].items():
 k='fundingRate'+venue;native=[f['final_hour_raw'][venue] if r['time']==f['window_to'] else r[k] for r in w];assert all(v is not None for v in native)
 vv=sorted(v*100*(8 if venue=='Hyperliquid' else 1) for v in native)
 got={'n':len(vv),'median_pct':median(vv),'min_pct':min(vv),'max_pct':max(vv),'q1_pct':vv[len(vv)//4],'q3_pct':vv[3*len(vv)//4],'last_pct':native[-1]*100*(8 if venue=='Hyperliquid' else 1)}
 assert all(abs(D(str(got[k]))-D(str(expected[k])))<D('1e-15') for k in got)
 fund.append({'venue':venue,**got,'finalNativeRate':native[-1],'nativeIntervalHours':1 if venue=='Hyperliquid' else 8,'materialFinalHourChange':abs(f['final_hour_raw'][venue]-f['final_hour_at_0843_read'][venue])>D('1e-12'),'absoluteFinalHourRateDifference':abs(f['final_hour_raw'][venue]-f['final_hour_at_0843_read'][venue])})
# Compare documented UTC windows, the original timezone-dependent expression and
# half-open alternative explicitly. Jitter is retained, not rounded into new rows.
eps=read(ORIG/'_fcap_verify_0820.json')['episodes'];episodes=[]
for sym,o in eps.items():
 rr=rows('episode',sym);lo,hi=map(ms,o['window'])
 def stats(a,b,closed=False):
  y=[r for r in rr if a<=r['fundingTime'] and (r['fundingTime']<=b if closed else r['fundingTime']<b)];v=[D(r['fundingRate']) for r in y];gaps=Counter(round((y[i+1]['fundingTime']-y[i]['fundingTime'])/3600000) for i in range(len(y)-1));return {'n':len(y),'atOrPast2Percent':sum(abs(z)>=D('.02') for z in v),'atOrPast1_99Percent':sum(abs(z)>=D('.0199') for z in v),'roundedHourGapCounts':dict(sorted(gaps.items())),'first':iso(y[0]['fundingTime']) if y else None,'last':iso(y[-1]['fundingTime']) if y else None}
 e={'symbol':sym,'originalPrintedWindow':o['window'],'originalCount':o['n_in_window'],'explicitUtcInclusive':stats(lo,hi,True),'explicitUtcHalfOpen':stats(lo,hi),'oneHourEarlierInclusiveSensitivity':stats(lo-3600000,hi-3600000,True)}
 if sym=='ALPACAUSDT':
  final=ms('2025-04-30T08:00:00Z');e['announcedLastSettlement']='2025-04-30T08:00:00Z';e['throughAnnouncedLastSecond']=stats(lo,final+1000);e['apiRowsAfterAnnouncedLastSecond']=[r for r in rr if r['fundingTime']>=final+1000]
  valid=[r for r in rr if ms('2025-04-24T18:00:00Z')<=r['fundingTime']<final+1000];e['atDocumentedLimitBeforeDelisting']=sum(abs(D(r['fundingRate']))==(D('.02') if r['fundingTime']<ms('2025-04-29T10:00:00Z') else D('.04')) for r in valid)
 episodes.append(e)
# Native rate/cap ratio never divides an 8h-normalized hourly rate by an hourly cap.
headroom={'binance':D('.0001')/D('.003')*100,'bitget':D('.0001')/D('.003')*100,'okx':D('.0001')/D('.00375')*100,'bybit':f['final_hour_raw']['Bybit']/D('.00333')*100,'hyperliquid':f['final_hour_raw']['Hyperliquid']/D('.04')*100}
board=read(ORIG/'_fcap_artifact_0820.json')['binance_rows_full'];assert len(board)==570 and len({r['symbol'] for r in board})==570
summaries=read(ORIG/'_fcap_hist_0820.json')['per_symbol'];summaries.update(read(ORIG/'_fcap_deep_0820.json')['retried_unicode_symbols'])
ratios=[r['cap']/r['max'] for r in summaries.values() if r['max']>0]
summary_replay={'nContracts':len(summaries),'settlementRows':sum(r['n'] for r in summaries.values()),'positiveMaxDenominator':len(ratios),'excludedNonpositiveMaximum':[s for s,r in summaries.items() if r['max']<=0],'medianCapOverPositiveMax':median(ratios),'atLeast30':sum(r>=30 for r in ratios),'atLeast10':sum(r>=10 for r in ratios),'sameReferenceFloorMatches':sum(r['at_floor'] for r in summaries.values()),'sameReferenceCapMatches':sum(r['at_cap'] for r in summaries.values()),'evidenceKind':'Original per-symbol aggregate arithmetic, not original raw-response verification; later exact-bound requery separate.'}
result={'checkedAt':ARCH['reviewedAt'],'kind':'Independent numerical and methodological audit; no historical-cap identity inferred from current reference','panel':panel,'yearDifferences':year_differences,'btcOriginalAll7609RowsMatchLaterQuery':True,'usdmPanelN':sum(x['n'] for x in panel if x['board']=='usdm'),'board':{'n':len(board),'symmetric':sum(r['cap']==-r['floor'] for r in board),'intervalHours':dict(Counter(r['interval_h'] for r in board)),'capsTighterThan2Percent':sum(r['cap']<D('.02') for r in board)},'feedReconstruction':{'inputs':'23 completed hourly rows from08:43 capture plus separately saved final08:00 hour from09:24. All published aggregates agree within1e-15percentagepoints; final full response envelope unavailable.','from':f['window_from'],'through':f['window_to'],'venues':fund,'capUsageNativePercent':headroom},'episodes':episodes,'originalSweepAggregateReplay':summary_replay,'limits':['Historical cap configuration timeline not recovered for the entire sample; reference matches cannot establish binding frequency.','Episode original request URLs and process timezone missing; one-hour shift reproduces counts but does not establish historical process timezone.','ALPACA current endpoint includes rows after officially announced last funding; keep separate and do not call them established payments.','Full original569-contract response archive and exact board exchangeInfo remain missing; later567-contract exact-bound requery is separate.']}

# Each archived body hash is checked before parsing. Original summary matches do
# not establish identity with missing original individual responses.
sweep=[]; floor_dates=[]
for name,envelope in sorted(ARCH['laterQueries']['cap-sweep-requery'].items()):
 assert hashlib.sha256(envelope['body'].encode()).hexdigest()==envelope['bodySha256']
 rr=json.loads(envelope['body']); symbol=name[:-5]; o=summaries[symbol]
 assert len(rr)<1000 and len(rr)==len({r['fundingTime'] for r in rr})
 assert all(r['symbol']==symbol and o['first_ms']<=r['fundingTime']<=o['last_ms'] for r in rr)
 assert all(rr[i]['fundingTime']<rr[i+1]['fundingTime'] for i in range(len(rr)-1))
 v=[D(r['fundingRate']) for r in rr]
 got={'symbol':symbol,'n':len(v),'min':min(v),'max':max(v),'atCap':sum(z>=o['cap'] for z in v),'atFloor':sum(z<=o['floor'] for z in v),'distinctRates':len(set(v)),'spanDays':D(o['last_ms']-o['first_ms'])/86400000,'intervalHours':o['interval_h']}
 for k,ok in [('n','n'),('min','min'),('max','max'),('atCap','at_cap'),('atFloor','at_floor'),('distinctRates','distinct_rates')]:assert got[k]==o[ok],(symbol,k,got[k],o[ok])
 floor_dates.extend(iso(r['fundingTime']) for r in rr if symbol!='ONEUSDT' and D(r['fundingRate'])<=o['floor'])
 sweep.append(got)
assert len(sweep)==567 and sum(x['n'] for x in sweep)==280101
result['laterSweep']={'contracts':len(sweep),'records':sum(x['n'] for x in sweep),'originalAggregateDifferences':0,'atReferenceCap':sum(x['atCap'] for x in sweep),'atReferenceFloor':sum(x['atFloor'] for x in sweep),'floorMatchesExcludingOneByMonth':dict(sorted(Counter(t[:7] for t in floor_dates).items())),'medianObservedSpanDays':{str(h):median([r['spanDays'] for r in sweep if r['intervalHours']==h]) for h in [4,8]},'rows':sweep,'limits':'567 exact original bounds. Two additional Unicode summaries lack those bounds. Later responses are not original response identities.'}
# Verify exchange monthly ZIPs against separately fetched published checksums;
# compare timestamp and exact decimal rate with the same UTC episode window.
monthly_rows={}
for meta in ARCH['monthlyManifest']:
 name=meta['url'].split('/')[-1]; raw=base64.b64decode(ARCH['monthlyArchiveBase64'][name]); checksum=base64.b64decode(ARCH['monthlyArchiveBase64'][name+'.CHECKSUM']).decode().split()[0]
 assert hashlib.sha256(raw).hexdigest()==checksum==meta['sha256']
 with zipfile.ZipFile(io.BytesIO(raw)) as z:
  assert len(z.namelist())==1
  for row in csv.DictReader(io.StringIO(z.read(z.namelist()[0]).decode())):monthly_rows[int(row['calc_time'])]=D(row['last_funding_rate'])
alpaca=[r for r in rows('episode','ALPACAUSDT') if ms('2025-04-20T00:00:00Z')<=r['fundingTime']<=ms('2025-05-05T00:00:00Z')]
assert len(alpaca)==269 and all(monthly_rows[r['fundingTime']]==D(r['fundingRate']) for r in alpaca)
result['monthlyAlpacaCheck']={'matchedUtcWindowRows':269,'publishedChecksumsVerified':2,'archiveRows':len(monthly_rows),'limits':'Same exchange as REST, not an independent contemporaneous provider. Agreement does not establish post-delisting payments.'}
result['btcSeries']=[[r['fundingTime'],r['fundingRate']] for r in rows('panel','BTCUSDT')]
result['sourceArchive']={'path':'docs/seo/evidence/2026-10-24-cap-review-inputs.json.gz','sha256':hashlib.sha256((ROOT/'2026-10-24-cap-review-inputs.json.gz').read_bytes()).hexdigest()}
result['sourceResponses']=[{'file':name,**{k:env[k] for k in ['url','retrievedAt','bodySha256']}} for source in ARCH['laterQueries'].values() for name,env in source.items()]
result['originalSources']=ARCH['originalSourceSha256'];result['monthlySources']=ARCH['monthlyManifest']
output=ROOT.parents[2]/'products/athenum-analytics/apps/marketing/public/research/funding-cap-review-20261024.json'
output.write_text(json.dumps(result,default=str,ensure_ascii=False,indent=2)+'\n')
print('PASS: 97,802 panel rows, BTC7,609 exact pairs; 567/280,101 sweep, two monthly checksums and269ALPACA pairs; published',output.name)
