"""Structural rigor: invariant property tests over 5000 randomized trials."""
import numpy as np
from sae14 import (purity, blockers, shakti_effective, belief_total,
                   awareness_raw, shakti_effective as sh, C_HUMAN)

rng = np.random.default_rng(7)
N = 5000
fails = {"blockers_monotone": 0, "purity_monotone": 0,
         "constraint_monotone": 0, "stage_gate": 0, "ranges": 0}

for _ in range(N):
    P = rng.random(6); B = rng.random(12)
    strength, stability = rng.random(), rng.random()
    phys, mental = rng.random(), rng.random()
    B1, B2 = rng.uniform(-1, 1), rng.uniform(-1, 1)

    pur = purity(P); blk = blockers(B)
    sh_eff = shakti_effective(strength, stability, phys, mental)
    bt = belief_total(B1, B2, stage=2)

    # range checks
    if not (0 <= pur <= 1 and 0 <= blk <= 1 and 0 <= sh_eff <= 1 and -1 <= bt <= 1):
        fails["ranges"] += 1

    base = awareness_raw(bt, pur, blk, sh_eff)

    # 1. Increasing Blockers must not increase Awareness when belief_total>0
    if bt > 0:
        blk2 = min(1.0, blk + 0.1)
        if awareness_raw(bt, pur, blk2, sh_eff) > base + 1e-9:
            fails["blockers_monotone"] += 1

    # 2. Increasing Purity must not decrease Awareness when belief_total>0
    if bt > 0:
        pur2 = min(1.0, pur + 0.1)
        if awareness_raw(bt, pur2, blk, sh_eff) < base - 1e-9:
            fails["purity_monotone"] += 1

    # 3. Increasing constraints must not increase Shakti_effective
    sh_more = shakti_effective(strength, stability, min(1, phys + 0.1), mental)
    if sh_more > sh_eff + 1e-9:
        fails["constraint_monotone"] += 1

    # 4. stage gate
    if belief_total(B1, B2, stage=0) != 0.5 or belief_total(B1, B2, stage=1) != 0.4:
        fails["stage_gate"] += 1

print("Structural invariant tests over", N, "trials")
for k, v in fails.items():
    print(f"  {k:22s}: {'PASS' if v==0 else f'FAIL ({v})'}")
print("OVERALL:", "PASS" if sum(fails.values()) == 0 else "FAIL")
