from pathlib import Path
import re, random, math

HERE=Path(__file__).resolve().parent
PAPER=HERE/"CSM_RH_Paper_61_Local_Increment_Correction_and_Corrected_Exceptional_Set_Gate_v0.1_2026-09-08.md"

def psi_loc_dp(d,tau,nu,c,p):
    return min(nu,max(d-tau,0)+c/p,d+tau*(1-d))

def check_p_optimal():
    random.seed(61)
    for _ in range(20000):
        d=random.uniform(0.01,0.49)
        tau=random.uniform(0.001,0.95)
        nu=random.uniform(0.001,0.8)
        c=random.uniform(0.001,1.0)
        b=psi_loc_dp(d,tau,nu,c,1)
        for p in [1.1,1.5,2,3,5,10]:
            assert psi_loc_dp(d,tau,nu,c,p)<=b+1e-14
    return True

def check_strict_gate():
    random.seed(610)
    for _ in range(30000):
        d=random.uniform(0.01,0.49)
        tau=random.uniform(0.001,0.95)
        nu=random.uniform(0.001,0.9)
        c=random.uniform(0.001,0.9)
        amp=psi_loc_dp(d,tau,nu,c,1)>d+1e-12
        gate=(nu>d and c>min(d,tau))
        assert amp==gate,(d,tau,nu,c,psi_loc_dp(d,tau,nu,c,1),amp,gate)
    return True

def check_piecewise_model():
    for d in [0.1,0.25,0.4]:
        # tau <= d: one jump per chain
        tau=d/2
        exponent_bad=1-tau
        assert abs((1-exponent_bad)-tau)<1e-14
        # tau > d: N^(tau-d) jumps per N^(1-tau) chains
        tau=(d+1)/2
        exponent_bad=(1-tau)+(tau-d)
        assert abs(exponent_bad-(1-d))<1e-14
    return True

def check_pintz_exponent():
    for d in [0.1,0.25,0.4]:
        for tau in [0.05,0.2,0.6]:
            lower=2-d-tau
            sup=1-max(d,tau)
            exc=lower-sup
            assert abs(exc-(1-min(d,tau)))<1e-14
    return True

def check_gain_formula():
    random.seed(611)
    for _ in range(10000):
        d=random.uniform(0.01,0.49)
        tau=random.uniform(0.001,0.9)
        nu=d+random.uniform(0.001,0.2)
        c=min(d,tau)+random.uniform(0.001,0.2)
        dp=psi_loc_dp(d,tau,nu,c,1)
        gain=dp-d
        rhs=min(nu-d,c-min(d,tau),tau*(1-d))
        assert abs(gain-rhs)<1e-14
    return True

def check_source():
    s=PAPER.read_text(encoding="utf-8")
    forbidden=[
        r"(?<!\\)\\\(",
        r"(?<!\\)\\\)",
        r"(?<!\\)\\\[",
        r"(?<!\\)\\\]",
    ]
    for pat in forbidden:
        assert re.search(pat,s) is None,pat
    assert s.count("$$")%2==0
    tmp=re.sub(r"\$\$.*?\$\$","",s,flags=re.S)
    assert len(re.findall(r"(?<!\\)\$",tmp))%2==0
    return True

if __name__=="__main__":
    print("p_optimal",check_p_optimal())
    print("strict_gate",check_strict_gate())
    print("piecewise_model",check_piecewise_model())
    print("pintz_exponent",check_pintz_exponent())
    print("gain_formula",check_gain_formula())
    print("source_delimiters",check_source())
    print("PASS")
