#!/usr/bin/env python3
"""Independently check arithmetic in the published August 8 report.

Inputs are transcribed published aggregates, NOT recovered individual records.
This script cannot verify their acquisition, alignment, clustered tests or medians.
No network calls and no production data path. Run from any directory.
"""
from fractions import Fraction
from math import comb, sqrt
from pathlib import Path
import json

N = 496
WRONG = [13, 38, 59, 70, 75, 74, 82]
PAIRS = [(71, 5), (55, 14), (43, 23), (38, 29), (31, 27), (29, 24), (19, 22)]
SMALL = [13, 38, 57, 65, 67, 65, 69]
LARGE = [0, 0, 2, 5, 8, 9, 13]

def binomial_two_sided(wins, losses):
    n = wins + losses
    return min(Fraction(1), 2 * Fraction(sum(comb(n, j) for j in range(min(wins, losses) + 1)), 2**n))

def holm(values):
    out = [Fraction(0)] * len(values)
    previous = Fraction(0)
    for order, i in enumerate(sorted(range(len(values)), key=values.__getitem__)):
        previous = max(previous, min(Fraction(1), (len(values)-order)*values[i]))
        out[i] = previous
    return out

def wilson(k, n, z=1.959963984540054):
    p = k/n
    denominator = 1+z*z/n
    centre = (p+z*z/(2*n))/denominator
    half = z*sqrt(p*(1-p)/n+z*z/(4*n*n))/denominator
    return [100*(centre-half), 100*(centre+half)]

def fisher(a, b, c, d):
    row1, row2, successes = a+b, c+d, a+c
    denominator = comb(row1+row2, successes)
    numerator = comb(row1, a)*comb(row2, c)
    total = sum(comb(row1, x)*comb(row2, successes-x)
                for x in range(max(0, successes-row2), min(row1, successes)+1)
                if comb(row1, x)*comb(row2, successes-x) <= numerator)
    return Fraction(total, denominator)

def review():
    p = [binomial_two_sided(*x) for x in PAIRS]
    adjusted = holm(p)
    rows = []
    for i, ((wins, losses), wrong) in enumerate(zip(PAIRS, WRONG)):
        assert 79-wins+losses == wrong
        assert SMALL[i]+LARGE[i] == wrong
        rows.append({'bucketStartHoursBeforeSettlement':i+1,
                     'completedBucketAvailableNoEarlierThanHoursBefore':i,
                     'publishedWrong':wrong,'publishedN':N,'percent':100*wrong/N,
                     'naiveWilson95Percent':wilson(wrong,N),
                     'screenRightRuleWrong':wins,'screenWrongRuleRight':losses,
                     'nominalP':float(p[i]),'holmAdjustedP':float(adjusted[i]),
                     'holmRejectAtFivePercent':adjusted[i] < Fraction(1,20),
                     'finalMagnitudeSmallWrong':SMALL[i],
                     'finalMagnitudeLargeWrong':LARGE[i],
                     'finalMagnitudeSmallWilson95Percent':wilson(SMALL[i],N//2),
                     'finalMagnitudeLargeWilson95Percent':wilson(LARGE[i],N//2)})
    assert [i+1 for i,x in enumerate(adjusted) if x < Fraction(1,20)] == [1,2]
    venues = [('Binance',9,7,42),('Bybit',23,23,77),('OKX',15,14,66),('Bitget',23,21,63)]
    comparisons = []
    for i,(name,a,c,nc) in enumerate(venues):
        for other,b,d,nd in venues[i+1:]:
            comparisons.append({'venues':[name,other],
                                'naiveIndependentFisherAllP':float(fisher(a,124-a,b,124-b)),
                                'naiveIndependentFisherRetrospectiveSmallP':float(fisher(c,nc-c,d,nd-d))})
    venue_holm = holm([Fraction(fisher(a, 124-a, b, 124-b)) for (_, a, _, _), (_, b, _, _) in
                       [(venues[i], venues[j]) for i in range(4) for j in range(i+1, 4)]])
    for comparison, adjusted_p in zip(comparisons, venue_holm):
        comparison['holmAdjustedAcrossSixPairsAllP'] = float(adjusted_p)
    weights = []
    for n in [480,5760]:
        weights.append({'premiumSamples':n,'startOfLeadHourWeights':[
            float(Fraction((n*(8-h)//8)*(n*(8-h)//8+1),n*(n+1))) for h in range(1,8)]})
    return {'kind':'arithmetic_and_method_review_of_published_aggregates',
            'individualObservationsRecovered':False,
            'publishedWindowUtc':['2026-06-27T00:00:00Z','2026-08-08T08:00:00Z'],
            'publishedStamps':124,'publishedVenues':4,'publishedN':N,
            'rows':rows,'publishedBaselineWrong':79,'baselinePercent':100*79/N,
            'retrospectiveGroups':{'eachN':248,'splitBy':'absolute FINAL settled rate',
                                   'publishedMedianPercent':0.0048,
                                   'zeroOf248NaiveWilsonUpperPercent':wilson(0,248)[1],
                                   'notAnEarlyInputThreshold':True},
            'venues':[{'name':name,'allWrong':a,'allN':124,'smallWrong':c,'smallN':n,
                       'allWilson95Percent':wilson(a,124),'smallWilson95Percent':wilson(c,n)}
                      for name,a,c,n in venues],
            'leadDefinition':'Lead h is the Athenum hourly mean of the hour opening h hours before the stamp; it is first available h-1 hours before the stamp (lead 1 only at settlement).',
            'venueComparisons':comparisons,'premiumWeightArithmetic':weights,
            'publishedMedianAbsoluteErrorBps':[0.036,0.092,0.140,0.180,0.210,0.231,0.246],
            'publishedFourHourErrorQuartilesBps':[0.065,0.339],
            'publishedFinalHourErrorQuartilesBps':[0.013,0.072],
            'publishedExample':{'settlement':'2026-08-08T08:00:00Z','valuesPercent':[
                {'venue':'Binance','hour01to02':0.00434,'settled':0.00542},
                {'venue':'Bybit','hour01to02':-0.00665,'hour04to05':-0.00162,'hour05to06':0.00009,'settled':0.00389},
                {'venue':'OKX','hour01to02':0.00210,'hour03to04':-0.00008,'settled':0.00356},
                {'venue':'Bitget','hour01to02':-0.00226,'settled':-0.00010}]},
            'limits':['Counts transcribed from the original published report; no row-level acquisition verification.',
                      'Nominal binomial, Fisher and Wilson calculations assume independence not established for shared stamps or serial observations.',
                      'Holm arithmetic corrects seven tests, not the underlying dependence or retrospective design.',
                      'Hourly means cannot be traded at bucket start; final-hour mean completes at the settlement boundary.',
                      'Final-magnitude grouping uses future information, not an observable early threshold.',
                      'Published medians, gaps, timestamps, precision grids and clustered-test results need original records; not verified here.',
                      'Premium coefficient shares are a mathematical illustration, not final funding already fixed after nonlinear clamps.']}

if __name__ == '__main__':
    result = review()
    path = Path(__file__).resolve().parents[3]/'products/athenum-analytics/apps/marketing/public/research/funding-before-settlement-review-20261024.json'
    path.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n')
    print(json.dumps({'scope':result['kind'],'holmRejectLeads':[x['bucketStartHoursBeforeSettlement'] for x in result['rows'] if x['holmRejectAtFivePercent']], 'threeHourNominalP':result['rows'][2]['nominalP'],'threeHourHolmP':result['rows'][2]['holmAdjustedP'],'recordsRecovered':False}))
