"""
Tajwells Theoretical Research Lab (Non-Commercial)
Reproducible Demo: Entropy-Bounded Abstention ("Sage Protocol") + HMAC PDP/PEP Gate

Demonstrates Chow's (1970) reject-option risk-coverage tradeoff on a synthetic
3-class Gaussian classification task, paired with an RFC 2904-style PDP/PEP
cryptographic execution token check.
Note: Synthetic demonstration illustrating that abstention lowers error rate on
covered samples at the cost of lower coverage (abstention rate).
"""

import hashlib
import hmac
import math
import random


def shannon_entropy_bits(probs: list[float]) -> float:
    """Compute conditional Shannon entropy H(Y|X) in bits."""
    return -sum(p * math.log2(p) for p in probs if p > 1e-12)


def softmax_scores(x1: float, x2: float, centers: list[tuple[float, float]], sigma: float) -> list[float]:
    """Compute isotropic Gaussian posterior class probabilities via Bayes rule."""
    inv_2s2 = 1.0 / (2.0 * sigma * sigma)
    logits = [-((x1 - cx) ** 2 + (x2 - cy) ** 2) * inv_2s2 for cx, cy in centers]
    m = max(logits)
    exps = [math.exp(v - m) for v in logits]
    z = sum(exps)
    return [e / z for e in exps]


def issue_pep_token(secret_key: bytes, policy_pack: str, context: str) -> str:
    """Conceptual PDP -> PEP HMAC-SHA256 authorization token."""
    payload = f"{policy_pack}|{context}".encode("utf-8")
    return hmac.new(secret_key, payload, hashlib.sha256).hexdigest()


def verify_pep_token(secret_key: bytes, policy_pack: str, context: str, token: str) -> bool:
    expected = issue_pep_token(secret_key, policy_pack, context)
    return hmac.compare_digest(expected, token)


def main() -> None:
    rng = random.Random(42)
    centers = [(0.0, 1.2), (-1.1, -0.7), (1.1, -0.7)]
    sigma = 0.95
    n_samples = 5000
    secret_key = b"tajwells-lab-demo-key-non-secret"
    policy_pack = "SAGE_ENTROPY_GATE_V1"

    dataset = []
    for _ in range(n_samples):
        y_true = rng.randrange(3)
        cx, cy = centers[y_true]
        x1 = rng.gauss(cx, sigma)
        x2 = rng.gauss(cy, sigma)
        probs = softmax_scores(x1, x2, centers, sigma)
        y_pred = max(range(3), key=lambda i: probs[i])
        entropy = shannon_entropy_bits(probs)
        dataset.append((y_true, y_pred, entropy))

    print(f"Sage Protocol Abstention Tradeoff Demo (N={n_samples:,} synthetic samples, sigma={sigma})")
    print("-" * 74)
    print(f"{'Max Entropy ε':>14} | {'Covered':>9} | {'Coverage %':>10} | {'Abstain %':>10} | {'Error on Covered':>16}")
    print("-" * 74)

    for eps in (1.60, 1.10, 0.80, 0.50, 0.25):
        covered = 0
        errors = 0
        for y_true, y_pred, ent in dataset:
            ctx = f"ent={ent:.4f}|eps={eps:.2f}"
            if ent <= eps:
                token = issue_pep_token(secret_key, policy_pack, ctx)
                if verify_pep_token(secret_key, policy_pack, ctx, token):
                    covered += 1
                    if y_pred != y_true:
                        errors += 1

        cov_pct = (covered / n_samples) * 100.0
        abs_pct = 100.0 - cov_pct
        err_pct = (errors / covered) * 100.0 if covered else 0.0
        label = "No gate (1.60)" if eps > 1.58 else f"<= {eps:.2f} bits"
        print(f"{label:>14} | {covered:9,d} | {cov_pct:9.2f}% | {abs_pct:9.2f}% | {err_pct:15.2f}%")


if __name__ == "__main__":
    main()
