from pathlib import Path
import re, math, random

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

def check_lowfreq_condition():
    random.seed(63)
    for _ in range(10000):
        a=random.uniform(0.001,0.332)
        q=2+a/2+random.uniform(0.001,1.0)
        exponent=4-2*q
        assert exponent < -a
    return True

def check_cheb_tradeoff():
    random.seed(630)
    for _ in range(10000):
        a=random.uniform(0.02,0.32)
        b=random.uniform(0.001,a/2*0.9)
        maxc=a-2*b
        c=maxc*random.uniform(0.01,0.99)
        assert 2*b+c<a
        # mean-square W^-a, threshold W^-b => exceptional exponent a-2b
        assert c < a-2*b
    return True

def ratio(a):
    return a/(2+a/2)

def check_2_over_13():
    vals=[ratio(a) for a in [0.01,0.1,0.2,0.3,1/3-1e-9]]
    assert all(vals[i]<vals[i+1] for i in range(len(vals)-1))
    target=2/13
    assert abs(vals[-1]-target)<1e-8
    return vals[-1]

def check_anchor():
    random.seed(631)
    for _ in range(10000):
        d=random.uniform(0.001,0.499)
        tau2=random.uniform(0,0.99)
        saving=max(d-tau2,0)
        assert saving<=d+1e-15
    return True

def check_boundary_scale():
    # Algebra: F'_rho ~ x^(rho-1), lag H2 gives H2 X^-d,
    # scaling by H/H2 leaves H X^-d.
    for d in [0.05,0.2,0.45]:
        for tau in [0.01,0.1,0.4]:
            for tau2 in [0.0,min(tau/2,0.2),tau]:
                # exponent of scaled absolute amplitude:
                # H/H2 * H2 * X^-d = H X^-d
                lhs=(tau2-tau)+(1-tau2)-d
                rhs=(1-tau)-d
                assert abs(lhs-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("lowfreq_condition",check_lowfreq_condition())
    print("cheb_tradeoff",check_cheb_tradeoff())
    print("two_over_thirteen_limit",check_2_over_13())
    print("anchor",check_anchor())
    print("boundary_scale",check_boundary_scale())
    print("source_delimiters",check_source())
    print("PASS")
