"""Synthetic worked-case arithmetic. Python 3.10+, standard library only.
No network, trained model, robot or production benchmark. Run: python3 topic-cases.py
"""
from math import isclose, exp, log


def retry_value(p, attempts):
    assert 0 <= p <= 1 and attempts >= 0
    if attempts == 0:
        return 3.0
    return max(3.0, -1 + 10*p + (1-p)*retry_value(p, attempts-1))


def stop_distance(speed, delay, deceleration, margin):
    if min(speed, delay, margin) < 0 or deceleration <= 0:
        raise ValueError('Invalid physical parameters')
    return speed*delay + speed**2/(2*deceleration) + margin


def causal_weights(logits, query):
    # Exclude future positions before normalization; stable softmax on legal keys.
    legal = logits[:query+1]
    peak = max(legal)
    numerators = [exp(x-peak) for x in legal]
    return [x/sum(numerators) for x in numerators] + [0.0]*(len(logits)-len(legal))


def check():
    for p,n,expected in [(0.4,0,3),(0.4,1,4.8),(0.4,2,5.88),(0,2,3)]:
        assert isclose(retry_value(p,n), expected)
    for v,t,expected in [(0.2,0.1,0.05),(0.1,0.1,0.025),(0.2,0.2,0.07)]:
        assert isclose(stop_distance(v,t,1,0.01),expected)
    assert causal_weights([1,2,3],0) == [1.0,0.0,0.0]
    assert causal_weights([1,2,3],1) == causal_weights([1,2,10000],1)
    assert isclose(sum(causal_weights([1000,1001,1002],2)),1)
    weights = causal_weights([0, log(2), log(4)], 1)
    assert isclose(sum(w*v for w,v in zip(weights,[2,4,100])), 10/3)
    assert isclose(sum(w*v for w,v in zip(weights,[2,4,1000])), 10/3)
    full = causal_weights([0, log(2), log(4)], 2)
    assert isclose(sum(w*v for w,v in zip(full,[2,4,100])), 410/7)
    assert isclose(sum(w*v for w,v in zip(full,[2,4,1000])), 4010/7)
    original, compressed = sum([600,3200,3800,400]), sum([600,1600,2400,400])
    assert (original,compressed)==(8000,5000)
    assert (8192-original-1000,8192-compressed-1000)==(-808,2192)
    assert isclose((original-compressed)/original,.375)
    requests = list(range(100)) + list(range(10))
    # Pure deduplication fixture, not a network service or concurrency guarantee.
    assert len(requests)==110 and len(set(requests))==100
    assert [14/20,18/20,12/20,16/20]==[.7,.9,.6,.8]
    assert 14-12 == 18-16 == 2
    print('PASS: all six teaching-case calculations and causal invariance.')
    print('These checks do not establish model quality or physical safety.')

if __name__ == '__main__':
    check()
