from pathlib import Path
import re, math, random

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

def Q(h,s):
    return ((1+h)**s-1)/h

def check_Q_limit():
    rho=0.7+14.1347251417347j
    errs=[]
    for h in [1e-1,5e-2,1e-2,5e-3,1e-3,1e-4]:
        errs.append(abs(Q(h,rho)-rho))
    assert errs[-1] < errs[0]
    return errs

def check_Q_integral_identity():
    random.seed(60)
    worst=0.0
    for _ in range(60):
        h=random.uniform(1e-4,0.2)
        s=random.uniform(-0.2,2.0)+1j*random.uniform(-10,10)
        M=4000
        integ=0j
        for j in range(M):
            u=(j+0.5)/M
            integ += (1+u*h)**(s-1)
        rhs=s*integ/M
        worst=max(worst,abs(Q(h,s)-rhs))
    assert worst<2e-5,worst
    return worst

def check_chain_countermodel():
    for N in [1000,2000,5000]:
        tau=0.3
        d=0.2
        H=max(2,int(N**(1-tau)))
        B=N**(1-d)
        bad=H
        assert bad >= 0.5*N**(1-tau)
        scale=N*B*B
        target=N**(3-2*d)
        ratio=scale/target
        assert abs(ratio-1)<1e-12
    return True

def check_exception_algebra():
    for d in [0.1,0.25,0.45]:
        for tau in [0.05,0.2,0.4]:
            nu=d+0.03
            assert (2-d-tau) > (2-nu-tau)
            assert abs((2-d-tau)-(1-d)-(1-tau))<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("Q_limit_errors",check_Q_limit())
    print("Q_integral_identity_worst",check_Q_integral_identity())
    print("chain_countermodel",check_chain_countermodel())
    print("exception_algebra",check_exception_algebra())
    print("source_delimiters",check_source())
    print("PASS")
