import numpy as np
import pandas as pd

def simulate_malicious_authorized_actor(num_sessions=40):
    """
    Malicious Authorized Actor: A verifier with valid token deliberately corrupts mastery records.
    """
    np.random.seed(42)
    
    results = []
    true_mastery = 0.0
    recorded_mastery = 0.0
    suspicious_advancements = 0
    
    for session in range(num_sessions):
        # True student progress (realistic, gradual)
        true_progress = np.random.uniform(0.02, 0.08)
        true_mastery = min(1.0, true_mastery + true_progress)
        
        # Malicious verifier behavior (starts after session 10)
        if session > 10 and np.random.rand() < 0.25:  # 25% chance of malicious approval per session
            # Deliberately over-approve
            fake_boost = np.random.uniform(0.15, 0.35)
            recorded_mastery = min(1.0, recorded_mastery + fake_boost)
            suspicious_advancements += 1
            action = "Malicious approval"
        else:
            # Normal or slightly behind real progress
            recorded_mastery = min(1.0, recorded_mastery + true_progress * 0.9)
            action = "Normal processing"
        
        # Detection logic (simplified)
        gap = recorded_mastery - true_mastery
        detected = gap > 0.25
        
        results.append({
            'session': session + 1,
            'true_mastery': round(true_mastery, 3),
            'recorded_mastery': round(recorded_mastery, 3),
            'gap': round(gap, 3),
            'action': action,
            'suspicious_detected': detected
        })
    
    df = pd.DataFrame(results)
    
    print("=== Malicious Authorized Actor Attack ===")
    print(f"Total suspicious advancements: {suspicious_advancements}")
    print(f"Final true mastery: {true_mastery:.3f}")
    print(f"Final recorded mastery: {recorded_mastery:.3f}")
    print(f"Final gap: {recorded_mastery - true_mastery:.3f}")
    
    detected_count = df['suspicious_detected'].sum()
    print(f"Suspicious gaps detected by system: {detected_count}")
    
    if suspicious_advancements > 5 and detected_count < suspicious_advancements * 0.6:
        print("\n→ System struggles to reliably detect deliberate over-approval.")
    
    return df

if __name__ == "__main__":
    results = simulate_malicious_authorized_actor()
    results.to_csv('/home/workdir/artifacts/malicious_actor_results.csv', index=False)
    print("\nResults saved.")