#!/usr/bin/env python3
"""
Synthetic exact-decomposition Gram crosscheck for CSM_RH Paper 06.

This checks only linear-algebra identities.
It is not evidence for RH.
"""
import numpy as np
import csv

def run(N, R, seed):
    rng = np.random.default_rng(seed)
    pieces = rng.normal(size=(R, 2*N))
    pieces[:, 0] = 0.0
    a = pieces.sum(axis=0)

    A = np.cumsum(a)
    B = np.cumsum(pieces, axis=1)

    sl = slice(N, 2*N)
    J = float(np.sum(A[sl]**2))

    G = B[:, sl] @ B[:, sl].T
    ones = np.ones(R)
    gram_value = float(ones @ G @ ones)

    diag_envelope = float(np.sum(np.sqrt(np.maximum(np.diag(G), 0.0)))**2)
    return [N, R, J, gram_value, abs(J-gram_value), diag_envelope, J/diag_envelope]

rows = [
    run(32, 2, 3202),
    run(64, 3, 6403),
    run(96, 4, 9604),
    run(128, 5, 12805),
]

with open("campaign05_gram_neutrality_crosscheck.csv", "w", encoding="utf-8", newline="") as f:
    w = csv.writer(f)
    w.writerow([
        "N", "R", "J_direct", "J_gram", "identity_abs_error",
        "triangle_envelope", "J_over_triangle_envelope"
    ])
    w.writerows(rows)

print("PASS")
print("max_identity_abs_error", max(r[4] for r in rows))
