"""
Verification Suite for 10M-Spin Slot Datasets & RTP Matrices
SlotMath Research Group / Applied Probability Institute
"""

import csv
import sys
from pathlib import Path

if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8')

DATA_DIR = Path(__file__).parent.parent / "data" if (Path(__file__).parent.parent / "data").exists() else Path(__file__).parent

def verify_rtp_variance_dataset():
    path = DATA_DIR / "slot_rtp_variance_10m_spins.csv"
    if not path.exists():
        print(f"ERROR: {path} not found")
        sys.exit(1)
    
    with open(path, mode="r", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        count = 0
        for row in reader:
            actual = float(row["actual_rtp_pct"])
            theory = float(row["theoretical_rtp_pct"])
            se = float(row["se_pct"])
            ci_low = float(row["ci_95_low"])
            ci_high = float(row["ci_95_high"])
            
            # Check confidence interval formulation: CI_low < CI_high
            assert ci_low < ci_high, f"Invalid CI bounds in row {count}"
            assert abs((theory - 1.96 * se) - ci_low) < 0.05, f"CI low mismatch in row {count}"
            assert abs((theory + 1.96 * se) - ci_high) < 0.05, f"CI high mismatch in row {count}"
            count += 1
            
    print(f"✓ Verified {count} Monte Carlo spin convergence records (SE and 95% CI integrity passed).")

def verify_operator_matrix():
    path = DATA_DIR / "operator_rtp_configuration_matrix.csv"
    if not path.exists():
        print(f"ERROR: {path} not found")
        sys.exit(1)
        
    with open(path, mode="r", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        count = 0
        for row in reader:
            cert_max = float(row["certified_max_rtp"])
            mga_tier = float(row["mga_tier2_rtp"])
            tax_tier = float(row["tax_heavy_rtp"])
            severe = float(row["severe_cut_rtp"])
            
            # Verify strict descending hierarchy: cert_max > mga_tier > tax_tier > severe
            assert cert_max > mga_tier > tax_tier > severe, f"RTP tier monotonicity failure in {row['slot_title']}"
            assert cert_max >= 96.0, f"Certified max RTP below 96% in {row['slot_title']}"
            count += 1
            
    print(f"✓ Verified {count} slot operator configuration benchmarks (RTP profile ordering validated).")

if __name__ == "__main__":
    print("[SlotMath Research Dataset Audit]")
    verify_rtp_variance_dataset()
    verify_operator_matrix()
    print("✓ All research datasets verified successfully.")
