#!/usr/bin/env python3
"""Reed's standalone synthetic illustration: error mass, metric, budget and sampling.
Run with Python 3 (standard library only): python3 sampling-premises.py > results.json
This file makes no network calls and reads no local data. No theorem reproduction.
Permission: copy, run and adapt this standalone example with credit to Reed.
"""
from fractions import Fraction as F
import json
import math
import random


def exact_risk(interval, radius, metric):
    if radius < 0 or metric not in ('euclidean', 'discrete'):
        raise ValueError('Invalid radius or metric')
    if interval is None:
        return F(0)
    a, b = interval
    if not 0 <= a <= b <= 1:
        raise ValueError('Interval outside [0,1]')
    if metric == 'discrete':
        return F(1) if radius >= 1 else b-a
    return min(F(1), b+radius)-max(F(0), a-radius)


def reachable_by_witness(x, interval, radius, metric):
    """Independent membership check: choose the nearest point of the closed set."""
    if interval is None:
        return False
    a, b = interval
    witness = a if x < a else b if x > b else x
    distance = abs(x-witness) if metric == 'euclidean' else F(x != witness)
    return distance <= radius


def run():
    # Expectations are fixed independently of exact_risk, using elementary lengths.
    cases = [
        ('small boundary interval', (F(0), F('0.01')), F('0.05'), F('0.06'), F('0.01')),
        ('full budget', (F(0), F('0.01')), F(1), F(1), F(1)),
        ('singleton', (F(0), F(0)), F('0.05'), F('0.05'), F(0)),
        ('empty set', None, F(1), F(0), F(0)),
        ('centered interval', (F('0.495'), F('0.505')), F('0.05'), F('0.11'), F('0.01')),
        ('zero budget', (F(0), F('0.01')), F(0), F('0.01'), F('0.01')),
        ('right boundary clipping', (F('0.99'), F(1)), F('0.05'), F('0.06'), F('0.01')),
        ('entire domain', (F(0), F(1)), F(0), F(1), F(1)),
    ]
    rows = []
    n_grid = 10000
    for name, interval, radius, euclid_expected, discrete_expected in cases:
        baseline = F(0) if interval is None else interval[1]-interval[0]
        row = dict(case=name, interval=None if interval is None else [str(v) for v in interval],
                   radius=str(radius), baseline_exact=str(baseline), metrics={})
        for metric, expected in [('euclidean', euclid_expected), ('discrete', discrete_expected)]:
            exact = exact_risk(interval, radius, metric)
            if exact != expected:
                raise AssertionError((name, metric, exact, expected))
            hits = sum(reachable_by_witness(F(2*i+1, 2*n_grid), interval, radius, metric)
                       for i in range(n_grid))
            grid = F(hits, n_grid)
            if abs(grid-exact) > F(2, n_grid):
                raise AssertionError('Independent grid disagrees with exact measure')
            row['metrics'][metric] = dict(risk_exact=str(exact), risk=float(exact), grid_hits=hits,
                                          grid_size=n_grid, grid_risk=float(grid))
        rows.append(row)
    # Genuine IID draws, not midpoint quadrature, for the zero-hit sampling check.
    seed, trials, sample_size = 20260914, 20000, 100
    rng = random.Random(seed)
    sampling = []
    for p in (0.001, 0.01, 0.05):
        misses = sum(all(rng.random() >= p for _ in range(sample_size)) for _ in range(trials))
        expected = (1-p)**sample_size
        observed = misses/trials
        se = math.sqrt(expected*(1-expected)/trials)
        if abs(observed-expected) > 6*se+1/trials:
            raise AssertionError('Monte Carlo mismatch exceeds diagnostic tolerance')
        sampling.append(dict(p=p, n=sample_size, trials=trials, zero_hit_trials=misses,
                             observed_zero_hit_fraction=observed, exact_zero_hit_probability=expected,
                             monte_carlo_standard_error=se))
    return dict(author='Reed', scope='Synthetic probability/geometry illustration; not a theorem or environment reproduction',
                distribution='Uniform Lebesgue probability on [0,1]',
                target='T(x)=0; procedure is 1 on the stated closed error set and 0 elsewhere',
                risk_definition='Pr_X[exists y with d(X,y)<=radius and P(y)!=T(y)]',
                cases=rows, sampling_seed=seed, sampling=sampling,
                checks={'exact_scenario_metric_pairs':len(cases)*2,'independent_grid_pairs':len(cases)*2,'iid_sampling_cases':len(sampling),'passed':True},
                limitations=['Midpoint grids and floating RNG draws do not prove measure-zero claims.',
                             'One-dimensional examples do not test Levy-family or high-dimensional concentration bounds.',
                             'The same numeric radius in different metrics is not the same physical edit budget.',
                             'No real agent behavior, classifier accuracy or directory impact measured.'])


if __name__ == '__main__':
    print(json.dumps(run(), indent=2))
