from pathlib import Path
import re, math, random

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

def kernel(m,a,b):
    z=complex(a,b)
    return (1/(z**(m+1))).real

def check_higher_derivative_sign_loss():
    for m in range(1,20):
        theta=math.pi/(m+2)
        a=1.0
        b=math.tan(theta)
        val=kernel(m,a,b)
        assert val < -1e-12,(m,val)
        assert kernel(m,a,0.0)>0
    return True

def check_boundary_scale():
    for k in [0.1,0.3,0.6,0.9]:
        for N in [10**4,10**6,10**8]:
            rel=N**(-k/2)
            assert 0<rel<1
    return True

def check_log_wall():
    # Directly compare using log(gamma), avoiding construction of huge gamma.
    for d in [0.01,0.05,0.2,0.45]:
        log_gamma=10.0/d
        target=1.0/d
        arch=0.5*log_gamma
        assert arch>target
        # A fixed d is eventually much larger than 1/log gamma.
        assert d > 1.0/log_gamma
    return True

def check_componentwise_norm():
    random.seed(58)
    for _ in range(1000):
        L=random.randint(2,10)
        norms=[10**random.uniform(-2,2) for _ in range(L)]
        coeff=[random.uniform(-2,2) for _ in range(L)]
        lhs_upper=sum(abs(c)*n for c,n in zip(coeff,norms))
        maxscale=max(n*n for n in norms)
        C=sum(abs(c) for c in coeff)**2
        assert lhs_upper**2 <= C*maxscale + 1e-10
    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("higher_derivative_sign_loss",check_higher_derivative_sign_loss())
    print("boundary_scale",check_boundary_scale())
    print("log_wall",check_log_wall())
    print("componentwise_norm",check_componentwise_norm())
    print("source_delimiters",check_source())
    print("PASS")
