from pathlib import Path
import random, cmath, re, json, csv

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

def g(N,t,x):
    return ((2*N/x)**(1j*t)-1)/x

def K_direct(N,rho,t):
    return sum((m**rho)*(g(N,t,m)-g(N,t,m+1)) for m in range(N,2*N))/rho

def A(N,rho,t):
    return sum(
        (m**(rho-1-1j*t))*(1-(m/(m+1))**(1+1j*t))
        for m in range(N,2*N)
    )/rho

def check_exact_response():
    worst=0.0
    for N in [5,11,29,47]:
        for rho in [0.5+14.1347251417347j,0.7+20.3j,0.35+31.1j]:
            for t in [-7.0,-0.3,0.0,0.1,1.4,8.2]:
                kd=K_direct(N,rho,t)
                ka=(2*N)**(1j*t)*A(N,rho,t)-A(N,rho,0.0)
                worst=max(worst,abs(kd-ka))
    assert worst<1e-11, worst
    return worst

def check_centering():
    worst=0.0
    for N in [5,17,41]:
        for rho in [0.5+14.1j,0.73+25j]:
            worst=max(worst,abs(K_direct(N,rho,0.0)))
    assert worst<1e-13, worst
    return worst

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("exact_response_worst_error",check_exact_response())
    print("centering_worst_error",check_centering())
    print("source_delimiters",check_source())
    print("PASS")
