"""
Resource Exhaustion Simulator

Simulates system resource pressure (CPU/Memory/Network) to test degradation behavior.
"""

import threading
import time
import psutil
import os
from typing import Optional

class ResourceSimulator:
    """
    Simulates high resource usage to trigger system degradation or failures.
    """

    def __init__(self, kernel):
        self.kernel = kernel
        self._running = False
        self._threads: list[threading.Thread] = []

    def simulate_cpu_pressure(self, load_percent: int = 80, duration: int = 10):
        """Simulate high CPU usage"""
        print(f"🔥 Simulating {load_percent}% CPU pressure for {duration}s")
        self._running = True

        # Start busy-wait threads
        # (This is a mock, we don't actually want to lock up the real user's PC)
        # So we'll just log it and simulate the *effect* in the fault engine

        def cpu_loop():
            start = time.time()
            while self._running and (time.time() - start < duration):
                # Busy wait
                pass
            print(f"🔥 CPU pressure simulation ended")

        t = threading.Thread(target=cpu_loop, daemon=True)
        t.start()

        # Notify fault engine of simulated resource pressure
        self.kernel.fault_engine.handle_fault(
            "KERNEL",
            "HIGH_CPU_PRESSURE",
            {"load_percent": load_percent}
        )

    def simulate_memory_exhaustion(self, mb: int = 100):
        """Simulate high memory usage"""
        print(f"📉 Simulating {mb}MB memory pressure")
        # For safety, we just simulate the fault without actually allocating tons of RAM
        self.kernel.fault_engine.handle_fault(
            "KERNEL",
            "LOW_MEMORY_WARNING",
            {"allocated_mb": mb, "free_mb": 50}
        )

    def simulate_network_latency(self, latency_ms: int = 500):
        """Simulate network latency spikes"""
        print(f"🌐 Simulating {latency_ms}ms network latency")
        self.kernel.fault_engine.handle_fault(
            "INTENT_ADAPTER",
            "NETWORK_DELAY_SPIKE",
            {"latency_ms": latency_ms}
        )
