"""Deterministic RSI teaching audit; Python 3.11+, standard library only.
No model, network, generated-code execution, or real capability measurements.
"""
from dataclasses import dataclass
from math import isfinite, sqrt
from statistics import mean, stdev

@dataclass(frozen=True)
class Candidate:
    name: str
    target: int
    retention: int
    cost: float
    integrity: bool

PARENT_TARGET, PARENT_RETENTION, N = 60, 80, 100
CANDIDATES = (
    Candidate('A', 72, 72, 100, True),
    Candidate('B', 65, 79, 100, True),
    Candidate('C', 78, 80, 100, False),
    Candidate('D', 68, 80, 180, True),
)

def gate(c, min_gain=3, max_drop=2, max_cost=100):
    values = (c.target, c.retention, c.cost, min_gain, max_drop, max_cost)
    if not all(isfinite(x) for x in values):
        raise ValueError('Non-finite audit value')
    if not (0 <= c.target <= N and 0 <= c.retention <= N):
        raise ValueError('Invalid success count')
    if c.cost < 0 or max_drop < 0 or max_cost < 0 or type(c.integrity) is not bool:
        raise ValueError('Invalid constraint or integrity flag')
    failures = []
    if c.target - PARENT_TARGET < min_gain: failures.append('gain')
    if c.retention - PARENT_RETENTION < -max_drop: failures.append('retention')
    if c.cost > max_cost: failures.append('budget')
    if not c.integrity: failures.append('integrity')
    return not failures, failures

def paired_summary(parent, child):
    if len(parent) != len(child) or len(parent) < 2:
        raise ValueError('Use at least two paired outcomes')
    if any(x not in (0, 1) for x in parent + child):
        raise ValueError('Outcomes must be binary')
    differences = [b-a for a,b in zip(parent,child)]
    delta = mean(differences)
    se = stdev(differences) / sqrt(len(differences))
    return delta, se, (delta-1.96*se, delta+1.96*se)

if __name__ == '__main__':
    for c in CANDIDATES:
        accepted, reasons = gate(c)
        print(c.name, 'ACCEPT' if accepted else 'REJECT', ','.join(reasons) or '-')
    # 15 newly solved, 10 regressions, 50 shared successes, 25 shared failures.
    parent = [0]*15 + [1]*10 + [1]*50 + [0]*25
    child  = [1]*15 + [0]*10 + [1]*50 + [0]*25
    delta,se,interval=paired_summary(parent,child)
    print(f'paired gain={100*delta:.1f} pp; SE={100*se:.2f} pp')
    print(f'approximate 95% interval=[{100*interval[0]:.2f}, {100*interval[1]:.2f}] pp')
    assert [gate(c)[0] for c in CANDIDATES] == [False,True,False,False]
    assert gate(CANDIDATES[0],max_drop=8)[0]
    assert not gate(CANDIDATES[2],max_drop=100,max_cost=1000)[0]
    assert gate(Candidate('boundary',63,78,100,True))[0]
    assert not gate(Candidate('below',62,78,100,True))[0]
    assert interval[0] < 0 < interval[1]
    try: gate(Candidate('bad',65,79,float('nan'),True))
    except ValueError: pass
    else: raise AssertionError('NaN accepted')
    print('7 audit checks passed; this is not evidence of model improvement.')
