from pathlib import Path
import re, random, math

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

def check_markov_penalty():
    random.seed(86)
    for _ in range(10000):
        p=2*random.randint(1,8)
        theta=random.uniform(0.1,0.95)
        nu=random.uniform(0.001,0.4)
        beta=random.uniform(0.51,0.99)
        M=p*theta+p*beta-p
        exc=1+M-p*(theta-nu)
        target=1+p*(nu-(1-beta))
        assert abs(exc-target)<1e-12,(p,theta,nu,beta,exc,target)
    return True

def check_boundary_transition():
    for d in [0.02,0.1,0.23,0.49]:
        for p in [2,4,6,10]:
            at=1+p*(d-d)
            assert abs(at-1)<1e-14
            above=1+p*((d+0.01)-d)
            below=1+p*((max(0,d-0.01))-d)
            assert above>1
            if d>=0.01:
                assert below<1
    return True

def check_threshold_GT():
    random.seed(860)
    for _ in range(1000):
        tau=random.uniform(0.01,0.5)
        nu=random.uniform(0.01,0.3)
        d=random.uniform(0.01,0.4)
        A=random.uniform(0,4)
        A4=random.uniform(0,12)
        sigma=1-d
        mu2=(tau+nu)*(1-sigma)*A+2*sigma-1+2*nu
        mu4=(tau+nu)*(1-sigma)*A4+4*sigma-3+4*nu
        base2=1+2*(nu-d)
        base4=1+4*(nu-d)
        assert mu2+1e-12>=base2
        assert mu4+1e-12>=base4
    return True

def check_hard_T():
    for tau in [0.05,0.2,0.6]:
        for nu in [0.01,0.1,0.25]:
            theta=1-tau
            # X/T <= H X^-nu -> exponent 1-(tau+nu) = theta-nu
            lhs_exp=1-(tau+nu)
            rhs_exp=theta-nu
            assert abs(lhs_exp-rhs_exp)<1e-14
    return True

def check_gate_incompatibility():
    for d in [0.03,0.11,0.31]:
        nu=d+0.005
        for k in [1,2,3,5]:
            mu=1+2*k*(nu-d)
            assert mu>1
    return True

def check_source():
    s=PAPER.read_text(encoding="utf-8")
    for pat in [r"(?<!\\)\\\(",r"(?<!\\)\\\)",r"(?<!\\)\\\[",r"(?<!\\)\\\]"]:
        assert re.search(pat,s) is None
    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("markov_penalty",check_markov_penalty())
    print("boundary_transition",check_boundary_transition())
    print("threshold_GT",check_threshold_GT())
    print("hard_T",check_hard_T())
    print("gate_incompatibility",check_gate_incompatibility())
    print("source_delimiters",check_source())
    print("PASS")
