"""
CorvOS - 7-Day Stress Simulation
Multi-peak attack and recovery scenario with 168 NV sensors
"""
import numpy as np
import asyncio, sys, os, random
sys.path.insert(0, os.path.dirname(__file__))

class StressSimulation7Days:
    VERSION = "1.0"
    
    def __init__(self, system):
        self.sys = system
        self.hours = 24 * 7  # 168 horas
        self.hourly_log = []
        self.attack_events = []
        
    def _generate_attack_schedule(self) -> list:
        """Generate 5 coordinated attack peaks over 7 days"""
        attacks = []
        # Dia 1: Ataque leve (hora 10-14)
        attacks.append({"day": 1, "hour_start": 10, "hour_end": 14,
                        "intensity": 0.3, "type": "DDoS"})
        # Dia 2: Pico moderado (hora 02-06)
        attacks.append({"day": 2, "hour_start": 2, "hour_end": 6,
                        "intensity": 0.5, "type": "Decoherence"})
        # Dia 3: Ataque severo (hora 18-22)
        attacks.append({"day": 3, "hour_start": 18, "hour_end": 22,
                        "intensity": 0.8, "type": "Retrocausal_Hijack"})
        # Dia 5: Double tap (hora 08-12 e 20-24)
        attacks.append({"day": 5, "hour_start": 8, "hour_end": 12,
                        "intensity": 0.6, "type": "Phase_Spoofing"})
        attacks.append({"day": 5, "hour_start": 20, "hour_end": 24,
                        "intensity": 0.4, "type": "Sensor_Poison"})
        # Dia 7: Ataque final masivo (hora 12-18)
        attacks.append({"day": 7, "hour_start": 12, "hour_end": 18,
                        "intensity": 0.9, "type": "Eigenvalue_Manipulation"})
        return attacks
    
    def _get_attack_intensity(self, day: int, hour: int) -> float:
        for atk in self._generate_attack_schedule():
            if atk["day"] == day and atk["hour_start"] <= hour < atk["hour_end"]:
                return atk["intensity"]
        return 0.0
    
    async def run(self):
        attacks = self._generate_attack_schedule()
        print("=" * 70)
        print("  SIMULACAO DE ESTRESSE - 7 DIAS (168 HORAS)")
        print("  168 Sensores NV | 5 Picos de Ataque | Multi-Recovery")
        print("=" * 70)
        print()
        
        current_lambda = 0.999
        bio_sync = 0.72
        
        print(f"  {'Hora':>6} | {'Dia':>3} | {'Ataque':>22} | {'Lambda':>8} | {'BioSync':>7} | {'Status'}")
        print(f"  {'-'*6}-+-{'-'*3}-+-{'-'*22}-+-{'-'*8}-+-{'-'*7}-+-{'-'*20}")
        
        for hour in range(self.hours):
            day = (hour // 24) + 1
            hour_of_day = hour % 24
            attack_intensity = self._get_attack_intensity(day, hour_of_day)
            
            # Normalize: attack reduces lambda
            if attack_intensity > 0:
                current_lambda = max(0.85, current_lambda - attack_intensity * 0.05)
                bio_sync = max(0.4, bio_sync - attack_intensity * 0.03)
            else:
                # Recovery: natural + Bio-Link pulse
                current_lambda = min(0.999, current_lambda + 0.002)
                bio_sync = min(0.90, bio_sync + 0.005)
            
            # Log every 12 hours or on attack events
            if hour % 12 == 0 or attack_intensity > 0:
                status = "CRITICO" if current_lambda < 0.92 else \
                         "ALERTA" if current_lambda < 0.97 else "OK"
                current_atk_type = next(
                    (a["type"] for a in attacks if a["day"] == day and a["hour_start"] <= hour < a["hour_end"]),
                    ""
                )
                attack_str = f"{current_atk_type} ({attack_intensity:.0%})" if attack_intensity > 0 else ""
                print(f"  {hour:>6} | {day:>3} | {attack_str:>22} | {current_lambda:>8.5f} | {bio_sync:>7.2%} | {status}")
                
                self.hourly_log.append({
                    "hour": hour, "day": day, "hour_of_day": hour_of_day,
                    "lambda2": current_lambda, "bio_sync": bio_sync,
                    "attack_intensity": attack_intensity
                })
        
        # Summary
        print()
        print("=" * 70)
        print("  RESUMO - 7 DIAS DE ESTRESSE")
        print("=" * 70)
        lambdas = [h["lambda2"] for h in self.hourly_log]
        attacks_total = sum(1 for h in self.hourly_log if h["attack_intensity"] > 0)
        critical = sum(1 for h in self.hourly_log if h["lambda2"] < 0.92)
        print(f"  Lambda2 minimo: {min(lambdas):.5f}")
        print(f"  Lambda2 medio:  {np.mean(lambdas):.5f}")
        print(f"  Lambda2 final:   {lambdas[-1]:.5f}")
        print(f"  Horas em ataque: {attacks_total}")
        print(f"  Periodos criticos: {critical}")
        print(f"  Taxa de recuperacao: {100*(1 - critical/168):.1f}%")
        print()
        
        for atk in attacks:
            print(f"  Dia {atk['day']} ({atk['hour_start']:02d}h-{atk['hour_end']:02d}): "
                  f"{atk['type']} | Intensidade: {atk['intensity']:.0%}")
        
        print("=" * 70)
        return self.hourly_log
