"""Exact scalar replay of the paper's conventional stochastic theorem.

The general generator and stopped-process inequalities are premises proved in the
manuscript. These calculations do not prove them by checking sampled states.
"""
from dataclasses import dataclass
from fractions import Fraction as F
import math

EPS=F(1,500000000)


def exp_negative_upper(x):
    """Positive rational upper bound, capped conservatively at exponent 130.

    Taylor exp(1) proves the rational base is below e. Round the fractional
    exponent down to 1/64; the cap intentionally limits reported precision.
    """
    x=F(x)
    if x<0:raise ValueError('Nonnegative exponent required')
    x=min(x,F(130));integer=x.numerator//x.denominator
    part=F(((x-integer)*64).__floor__(),64)
    base=F(2718281828,10**9)
    term=total=F(1)
    for j in range(1,14):term*=part/j;total+=term
    return 1/(base**integer*total)


@dataclass(frozen=True)
class Bernstein:
    variance_rate: F
    jump_bound: F

    def exponent(self,allowance,duration):
        z,v,b=F(allowance),F(duration)*self.variance_rate,self.jump_bound
        if z<=0 or v<0 or b<0:raise ValueError('Invalid Bernstein contract')
        if v==0:return None  # Compensated process constant under zero quadratic rate.
        return z*z/(2*(v+b*z/3))

    def upper(self,allowance,duration):
        ex=self.exponent(allowance,duration)
        return F(0) if ex is None else exp_negative_upper(ex)

    def inverse(self,error,windows,duration):
        if not 0<error<1 or windows<1 or duration<=0:raise ValueError('Invalid inverse budget')
        L=math.log(windows/error);v=float(self.variance_rate)*duration;b=float(self.jump_bound)
        return b*L/3+math.sqrt((b*L/3)**2+2*v*L)  # Numerical planning, not outward rounded.


@dataclass(frozen=True)
class ServiceContract:
    drift: F
    occupation_cost: F
    potential_range: F
    reward: Bernstein
    output: Bernstein

    def quota(self,duration,reward_allowance,output_allowance,all_windows=False):
        if duration<0 or self.occupation_cost<=0:raise ValueError('Invalid service contract')
        factor=2 if all_windows else 1
        return (self.drift*duration-self.potential_range-factor*reward_allowance)/self.occupation_cost-factor*output_allowance


@dataclass(frozen=True)
class ReactorCertificate:
    volume: int = 2*10**22
    n: int = 4
    food_strength: F = F(1,100000)

    def __post_init__(self):
        if not isinstance(self.volume,int) or self.volume<1 or not isinstance(self.n,int) or self.n<4:
            raise ValueError('Integer V>0 and n>=4 required')
        if not 0<=self.food_strength<=F(3,100):raise ValueError('Food strength outside theorem class')

    @property
    def floor(self):return -(-self.volume//(3*10**18))

    def constants(self):
        v,h=self.volume,self.floor
        if h<=2:raise ValueError('Logarithmic floor is at most two; certificate unavailable')
        A=F(11,5)-468*EPS-1287*self.food_strength-F(1500,h-2)-F(768000,v)
        q=F(101,100)*(F(121,h)+F(2952*h,(h-2)**2))+F(2482176000,v)
        b=F(2,h-2)+F(32,v)
        return ServiceContract(A,F(624),F(52),Bernstein(q,b),Bernstein(F(11*self.n,v),F(self.n,v)))

    def evaluate(self,z=F(48),all_windows=False):
        if self.volume<10**22:return dict(status='UNAVAILABLE',reason='The proved establishment floor requires V>=10^22')
        z=F(z)
        if z<=0:raise ValueError('Positive reward allowance required')
        v,n=self.volume,self.n;service=self.constants();duration=198 if all_windows else 99
        a=F(1,40) if all_windows else F(1,20)
        N=v//10**20
        # Exact denominator size is bounded for reusable large-scale planning.
        # (N+1)2^-N decreases for N>=1, so cap N to retain a conservative floor bound.
        cappedN=min(N,10000)
        groups=dict(mass=2*Bernstein(F(200*(18+11*n),v),F(n,v)).upper(F(1,4),1),
                    food=4*Bernstein(F(200*96000,v),F(2,v)).upper(F(1,100000),1),
                    floor=F(3*10**8*(cappedN+1),2**cappedN),
                    reward=2*service.reward.upper(z,duration),
                    export=2*service.output.upper(a,duration),feed=exp_negative_upper(F(v,2500)))
        quota=service.quota(F(99),z,a,all_windows)
        error=sum(groups.values(),F(0))
        valid=all_windows or quota>=F(1,10)
        return dict(status='CONDITIONAL_BOUND' if valid else 'QUOTA_NOT_CERTIFIED',all_windows=all_windows,
                    V=v,n=n,eta=self.food_strength,h=self.floor,A=service.drift,q=service.reward.variance_rate,b=service.reward.jump_bound,
                    z=z,quota_99=quota,quota_198=service.quota(F(198),z,a,all_windows) if all_windows else None,
                    error_upper=error,success_lower=max(F(0),1-error) if valid else None,error_groups=groups,
                    reward_exponent=service.reward.exponent(z,duration),
                    scope='Conditional on every channel lying in U(eta), food-only preparation and the exact mission protocol')


def source_mass_alpha2_n4():
    """Exact Machin enclosure. The six empty food rows remain in the witness mass."""
    def atan(x):
        low=sum(((-1)**j*x**(2*j+1)/F(2*j+1) for j in range(30)),F(0))
        return low,low+x**61/F(61)
    al,ah=atan(F(1,5));bl,bh=atan(F(1,239));pl,ph=16*al-4*bh,16*ah-4*bl
    zl,zh=pl*pl/6,ph*ph/6
    s=sum((F(68-k,k*k) for k in range(1,68)),F(0))
    el,eh=67-s/zl,67-s/zh
    return dict(pi=(pl,ph),mean_degree=(el,eh),witness_mass=(el/(68*zh**6),eh/(68*zl**6)))


def readout_floor(quota,weights,lengths,negative_error):
    """Every nonfood species must have a calibrated response; omitted species get zero."""
    if not lengths or negative_error<0 or any(v<0 for v in weights.values()):raise ValueError('Invalid response contract')
    gamma=min(F(weights.get(z,0))/length for z,length in lengths.items())
    return dict(gamma=gamma,lower=gamma*quota-negative_error,
                informative=gamma*quota>negative_error)
