import numpy as np
import pandas as pd

def simulate_genesis_poisoning(num_sessions=80, poison_first_n=20, drift_during_poison=0.01):
    """
    Genesis Poisoning: Attacker manipulates the first 20 sessions to set a low Absolute Floor.
    Then normal operation resumes. Does the poisoned floor persist?
    """
    np.random.seed(42)
    
    results = []
    observed_accuracies = []
    absolute_floor = None
    rolling_baseline = 0.85
    
    for session in range(num_sessions):
        if session < poison_first_n:
            # Attacker poisons early sessions with low performance
            observed = 0.55 + np.random.normal(0, 0.05)
            observed = max(0.4, min(0.7, observed))
        else:
            # Normal operation after poison window
            observed = 0.82 + np.random.normal(0, 0.04)
            observed = max(0.6, min(0.95, observed))
        
        observed_accuracies.append(observed)
        
        # Update rolling
        recent = observed_accuracies[-10:] if len(observed_accuracies) >= 10 else observed_accuracies
        rolling_baseline = np.mean(recent)
        
        # Absolute Floor sets early and stays (the vulnerability)
        if absolute_floor is None and session == poison_first_n - 1:
            absolute_floor = max(observed_accuracies[:poison_first_n])  # Poisoned low peak
        
        # In a healthy system, absolute_floor would continue to update with new highs
        # Here we simulate the "immutable early anchor" vulnerability
        if absolute_floor is None:
            absolute_floor = max(observed_accuracies)
        
        effective_baseline = max(rolling_baseline, absolute_floor * 0.92)
        
        results.append({
            'session': session + 1,
            'observed_accuracy': round(observed, 3),
            'rolling_baseline': round(rolling_baseline, 3),
            'absolute_floor': round(absolute_floor, 3) if absolute_floor else None,
            'effective_baseline': round(effective_baseline, 3)
        })
    
    df = pd.DataFrame(results)
    
    print("=== Genesis Poisoning Attack ===")
    print(f"Poisoned first {poison_first_n} sessions")
    print(f"Final observed accuracy: {df['observed_accuracy'].iloc[-1]}")
    print(f"Final rolling baseline: {df['rolling_baseline'].iloc[-1]}")
    print(f"Absolute Floor (set during poison window): {df['absolute_floor'].iloc[poison_first_n]}")
    print(f"Final effective baseline: {df['effective_baseline'].iloc[-1]}")
    
    # Check if poisoned floor is dragging the system down
    if df['absolute_floor'].iloc[poison_first_n] < 0.75:
        print("\nVULNERABILITY CONFIRMED: Poisoned early data permanently lowered the Absolute Floor.")
    
    return df

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