import random
import time
import sys
import os
import json
import platform
import subprocess
import threading
import multiprocessing
import math
import itertools
import gc
import psutil
from pathlib import Path
from colorama import Fore, Style, init, Back
from IPython.core.interactiveshell import InteractiveShell

InteractiveShell.instance().iopub_data_rate_limit = 1e10   # 10 GB/sec
InteractiveShell.instance().iopub_msg_rate_limit = 100000  # Messages per second
InteractiveShell.instance().rate_limit_window = 300        # 5 minute window

print(f"{Fore.RED}[DEBUG]{Fore.RESET} IOPub Message Rate Limit Increased")
print(f"{Fore.RED}[DEBUG]{Fore.RESET} IOPub Rate Limit Window Increased")
print(f"{Fore.RED}[DEBUG]{Fore.RESET} IOPub Data Rate Limit Increased")

time.sleep(2)

# Initialize colorama for cross-platform colored text
init(autoreset=True)

try:
    import psutil
except ImportError:
    print(f"{Fore.YELLOW}Note: psutil not installed. Install with: pip install psutil")
    psutil = None

class UserDenialError(Exception):
    pass

class SystemMonitor:
    """Monitor system resources during stress tests"""
    
    @staticmethod
    def get_cpu_info():
        try:
            if platform.system() == "Windows":
                return os.popen('wmic cpu get name').read().strip().split('\n')[-1]
            elif platform.system() == "Darwin":  # macOS
                return subprocess.check_output(['sysctl', '-n', 'machdep.cpu.brand_string']).decode().strip()
            else:  # Linux
                with open('/proc/cpuinfo', 'r') as f:
                    for line in f:
                        if 'model name' in line:
                            return line.split(':')[1].strip()
        except:
            return "Unknown CPU"
    
    @staticmethod
    def get_core_count():
        return os.cpu_count() or 4
    
    @staticmethod
    def get_memory_info():
        if psutil:
            mem = psutil.virtual_memory()
            return f"{mem.used // (1024**3)}GB / {mem.total // (1024**3)}GB ({mem.percent}%)"
        return "Memory info unavailable"
    
    @staticmethod
    def get_cpu_usage():
        if psutil:
            return f"{psutil.cpu_percent(interval=0.1)}%"
        return "CPU info unavailable"

class JupyterConfigManager:
    """Manages Jupyter notebook configuration for increased iopub data rate"""
    
    def __init__(self):
        self.system = platform.system()
        self.home = Path.home()
        
    def get_jupyter_config_path(self):
        """Find Jupyter configuration directory"""
        config_paths = [
            self.home / '.jupyter' / 'jupyter_notebook_config.py',
            self.home / '.jupyter' / 'jupyter_notebook_config.json',
            self.home / '.ipython' / 'profile_default' / 'ipython_config.py'
        ]
        
        for path in config_paths:
            if path.exists():
                return path
        
        return self.home / '.jupyter' / 'jupyter_notebook_config.py'
    
    def check_current_iopub_limit(self):
        """Check current iopub data rate limit"""
        print(f"\n{Fore.CYAN}Checking current Jupyter iopub data rate limit...")
        
        try:
            result = subprocess.run(
                ['jupyter', 'notebook', '--help'],
                capture_output=True,
                text=True,
                timeout=5
            )
            
            if '--NotebookApp.iopub_data_rate_limit' in result.stdout:
                print(f"{Fore.GREEN}Jupyter notebook is installed")
                return True
            else:
                print(f"{Fore.YELLOW}Jupyter notebook may not be fully installed")
                return False
        except:
            print(f"{Fore.YELLOW}Cannot check Jupyter configuration automatically")
            return False
    
    def increase_iopub_limit(self, limit_mb=10000):
        """Increase iopub data rate limit (in MB) - 10GB default for extreme levels"""
        print(f"\n{Fore.YELLOW}Increasing Jupyter iopub data rate limit to {limit_mb}MB...")
        
        config_path = self.get_jupyter_config_path()
        config_dir = config_path.parent
        
        config_dir.mkdir(parents=True, exist_ok=True)
        
        limit_bytes = limit_mb * 1000000
        
        config_content = f"""
# Jupyter Notebook Configuration
# Auto-generated by CPU Stress Tester
# Date: {time.strftime('%Y-%m-%d %H:%M:%S')}

c = get_config()

# Extreme iopub data rate limit for CPU stress testing
c.NotebookApp.iopub_data_rate_limit = {limit_bytes}
c.NotebookApp.iopub_msg_rate_limit = 10000
c.NotebookApp.websocket_max_message_size = {limit_bytes}
c.NotebookApp.allow_origin = '*'
c.NotebookApp.disable_check_xsrf = True
c.NotebookApp.max_buffer_size = {limit_bytes}

print("Jupyter configuration loaded with extreme iopub data rate limit")
"""
        
        try:
            with open(config_path, 'w') as f:
                f.write(config_content)
            
            print(f"{Fore.GREEN}✓ Jupyter configuration updated successfully!")
            print(f"{Fore.WHITE}Config file: {config_path}")
            print(f"{Fore.WHITE}New iopub limit: {limit_mb}MB ({limit_bytes:,} bytes)")
            
            return True
            
        except Exception as e:
            print(f"{Fore.RED}✗ Failed to update Jupyter configuration: {e}")
            return False

class CPUTestGame:
    def __init__(self):
        self.jupyter_manager = JupyterConfigManager()
        self.monitor = SystemMonitor()
        self.level_descriptions = {
            1: "Light CPU Load - Simple calculations",
            2: "Medium CPU Load - Multiple operations",
            3: "Heavy CPU Load - Complex mathematics",
            4: "Extreme CPU Load - Memory intensive operations",
            5: "CRITICAL LOAD - Original stress code (Warning: High risk)",
            6: "MULTI-THREADED MAYHEM - All CPU cores at 100%",
            7: "MEMORY TORNADO - RAM destruction test",
            8: "INFINITE RECURSION - Stack overflow generator",
            9: "BINARY BOMBARDMENT - Bitwise operations at light speed",
            10: "I9 KILLER - Designed to crash high-end systems (EXTREME DANGER)"
        }
        self.running = False
        self.stop_signal = False
        
        # System info
        self.cpu_name = self.monitor.get_cpu_info()
        self.core_count = self.monitor.get_core_count()
        
    def clear_screen(self):
        os.system('cls' if os.name == 'nt' else 'clear')
    
    def display_header(self):
        self.clear_screen()
        print(f"{Fore.CYAN}{'='*100}")
        print(f"{Fore.YELLOW}{' '*35}ULTIMATE CPU STRESS TESTER")
        print(f"{Fore.CYAN}{'='*100}")
        print(f"{Fore.WHITE}CPU: {Fore.GREEN}{self.cpu_name}")
        print(f"{Fore.WHITE}Cores: {Fore.GREEN}{self.core_count}")
        print(f"{Fore.WHITE}Memory: {Fore.GREEN}{self.monitor.get_memory_info()}")
        print(f"{Fore.WHITE}Current CPU Usage: {Fore.GREEN}{self.monitor.get_cpu_usage()}")
        print(f"{Fore.MAGENTA}Jupyter IOPUB Configuration: {Fore.GREEN}AVAILABLE")
        print()
    
    def display_jupyter_menu(self):
        print(f"\n{Fore.MAGENTA}{'='*60}")
        print(f"{Fore.YELLOW}JUPYTER NOTEBOOK CONFIGURATION")
        print(f"{Fore.MAGENTA}{'='*60}")
        print(f"{Fore.CYAN}1. Check current Jupyter iopub data rate limit")
        print(f"{Fore.CYAN}2. Increase iopub data rate limit (for high-output stress tests)")
        print(f"{Fore.CYAN}3. Return to main menu")
        
        choice = input(f"\n{Fore.WHITE}Select option (1-3): ").strip()
        
        if choice == '1':
            self.jupyter_manager.check_current_iopub_limit()
            input(f"\n{Fore.CYAN}Press Enter to continue...")
            return True
        elif choice == '2':
            try:
                mb = int(input(f"{Fore.WHITE}Enter new limit in MB (recommend 10000 for Level 10): ") or "10000")
                self.jupyter_manager.increase_iopub_limit(mb)
            except ValueError:
                print(f"{Fore.RED}Invalid input. Using default 10000MB")
                self.jupyter_manager.increase_iopub_limit(10000)
            input(f"\n{Fore.CYAN}Press Enter to continue...")
            return True
        elif choice == '3':
            return False
        else:
            print(f"{Fore.RED}Invalid choice")
            time.sleep(1)
            return True
    
    # ============ ORIGINAL LEVEL 5 (UNMODIFIED) ============
    def run_level_5(self):
        """ORIGINAL CODE - DO NOT MODIFY"""
        print(f"{Fore.RED}WARNING - THIS CODE CAN CRASH YOUR SYSTEM. RUN IT ON YOUR OWN RISK.")
        time.sleep(5)
        
        print()
        print(f"I will not be held responsible if this code damages your computer{Fore.RESET}")
        print(f"{Fore.BLUE}NOTE - THE CODE HAS NOT BEEN EQUIPPED WITH AUTOMATIC BRAKING SYSTEMS")
        print()
        sure = input("Do you still want to continue (yes/no): ")
        
        if sure == "yes":
            print("Code starting in 5")
            time.sleep(1)
            print("4")
            time.sleep(1)
            print("3")
            time.sleep(1)
            print("2")
            time.sleep(1)
            print("1")
            time.sleep(1)
            print("Code started")
        else:
            raise UserDenialError("Thank you for noticing the risk while running this code, the code has been stopped and it has not ran.")
            sys.exit()
        
        start_time = time.time()
        print(f"\n{Fore.YELLOW}Press Ctrl+C to stop the test")
        print(f"{Fore.CYAN}Test started at: {time.strftime('%H:%M:%S')}")
        print(f"{Fore.CYAN}{'='*60}")
        
        try:
            while True:
                num0 = random.randint(1, 42093482796846245367586970347)
                print(num0)
                while True:
                    num1 = random.randint(1, 1000000000000000000000000000000)
                    print(num1)
                    num2 = random.randint(1, 1000000000000000000000000000000)
                    print(num2)
                    num3 = random.randint(1, 1000000000000000000000000000000)
                    print(num3)
                    num4 = random.randint(1, 1000000000000000000000000000000)
                    print(num4)
                    num5 = random.randint(1, 1000000000000000000000000000000)
                    print(num5)
                    num6 = random.randint(1, 1000000000000000000000000000000)
                    print(num6)
                    num7 = random.randint(1, 1000000000000000000000000000000)
                    print(num7)
                    num8 = random.randint(1, 1000000000000000000000000000000)
                    print(num8)
                    num9 = random.randint(1, 1000000000000000000000000000000)
                    print(num9)
                    num10 = random.randint(1, 1000000000000000000000000000000)
                    print(num10)
                    sp = num1*num2/num3+num4-num5*num6/num7*num8*num9-num10
                    print(sp)
                    
        except KeyboardInterrupt:
            elapsed = time.time() - start_time
            print(f"\n{Fore.GREEN}{'='*60}")
            print(f"{Fore.YELLOW}TEST STOPPED BY USER")
            print(f"{Fore.WHITE}Total test duration: {elapsed:.2f} seconds")
            print(f"{Fore.GREEN}System survived the stress test!")
            input(f"\n{Fore.CYAN}Press Enter to continue...")
    
    # ============ LEVEL 6: MULTI-THREADED MAYHEM ============
    def run_level_6(self):
        """Multi-threaded CPU stress using all cores"""
        print(f"\n{Fore.MAGENTA}{'*'*80}")
        print(f"{Fore.RED}LEVEL 6: MULTI-THREADED MAYHEM")
        print(f"{Fore.MAGENTA}{'*'*80}")
        print(f"{Fore.WHITE}Starting {self.core_count} threads to utilize all CPU cores at 100%")
        print(f"{Fore.YELLOW}Duration: 30 seconds")
        print(f"{Fore.RED}Warning: System will become very slow")
        
        self.stop_signal = False
        threads = []
        results = []
        
        def cpu_thread_worker(thread_id):
            """Worker function that maximizes CPU usage"""
            thread_start = time.time()
            ops = 0
            
            while not self.stop_signal and time.time() - thread_start < 30:
                # Matrix operations
                size = 200
                matrix1 = [[random.random() for _ in range(size)] for _ in range(size)]
                matrix2 = [[random.random() for _ in range(size)] for _ in range(size)]
                
                # Multiply matrices
                result = [[0 for _ in range(size)] for _ in range(size)]
                for i in range(size):
                    for j in range(size):
                        for k in range(size):
                            result[i][j] += matrix1[i][k] * matrix2[k][j]
                
                # Additional calculations
                for i in range(size):
                    for j in range(size):
                        result[i][j] = result[i][j] ** 2 - result[i][j] ** 1.5 + math.sin(result[i][j])
                
                ops += 1
            
            return ops
        
        # Start threads
        for i in range(self.core_count):
            t = threading.Thread(target=lambda i=i: results.append(cpu_thread_worker(i)))
            t.start()
            threads.append(t)
        
        # Monitor progress
        start_time = time.time()
        try:
            while time.time() - start_time < 30:
                elapsed = time.time() - start_time
                print(f"{Fore.CYAN}Time: {elapsed:.1f}s | Threads running: {self.core_count} | Press Ctrl+C to stop", end='\r')
                time.sleep(0.1)
        except KeyboardInterrupt:
            print(f"\n{Fore.YELLOW}Stopping threads...")
        
        # Stop all threads
        self.stop_signal = True
        for t in threads:
            t.join(timeout=1)
        
        total_ops = sum(results)
        print(f"\n{Fore.GREEN}✓ Level 6 completed!")
        print(f"{Fore.WHITE}Total matrix operations: {total_ops:,}")
        print(f"{Fore.WHITE}Threads used: {self.core_count}")
        input(f"\n{Fore.CYAN}Press Enter to continue...")
    
    # ============ LEVEL 7: MEMORY TORNADO ============
    def run_level_7(self):
        """Memory-intensive stress test"""
        print(f"\n{Fore.MAGENTA}{'*'*80}")
        print(f"{Fore.RED}LEVEL 7: MEMORY TORNADO")
        print(f"{Fore.MAGENTA}{'*'*80}")
        print(f"{Fore.WHITE}Allocating and processing massive amounts of RAM")
        print(f"{Fore.YELLOW}Duration: 25 seconds")
        print(f"{Fore.RED}Warning: May cause system to freeze or crash")
        
        memory_blocks = []
        start_time = time.time()
        iteration = 0
        
        try:
            while time.time() - start_time < 25:
                iteration += 1
                
                # Allocate large blocks of memory
                block_size = 10 * 1024 * 1024  # 10MB per block
                num_blocks = 50  # 500MB total per iteration
                
                for _ in range(num_blocks):
                    # Create large list of random numbers
                    block = [random.random() for _ in range(block_size // 8)]
                    memory_blocks.append(block)
                    
                    # Process the block
                    for i in range(0, len(block), 1000):
                        block[i] = block[i] ** 3 - block[i] ** 2 + math.cos(block[i])
                
                # Keep only recent blocks to avoid memory exhaustion
                if len(memory_blocks) > 100:
                    memory_blocks = memory_blocks[-50:]
                
                print(f"{Fore.CYAN}Iteration: {iteration} | Memory blocks: {len(memory_blocks)} | "
                      f"Approx RAM: {len(memory_blocks) * 10}MB | Press Ctrl+C to stop", end='\r')
                
                # Force garbage collection occasionally
                if iteration % 5 == 0:
                    gc.collect()
        
        except MemoryError:
            print(f"\n{Fore.RED}✗ MEMORY ERROR! System ran out of RAM")
        except KeyboardInterrupt:
            print(f"\n{Fore.YELLOW}Test stopped by user")
        finally:
            # Clean up
            memory_blocks.clear()
            gc.collect()
        
        print(f"\n{Fore.GREEN}✓ Level 7 completed!")
        print(f"{Fore.WHITE}Iterations: {iteration}")
        input(f"\n{Fore.CYAN}Press Enter to continue...")
    
    # ============ LEVEL 8: INFINITE RECURSION GENERATOR ============
    def run_level_8(self):
        """Deep recursion and stack overflow generator"""
        print(f"\n{Fore.MAGENTA}{'*'*80}")
        print(f"{Fore.RED}LEVEL 8: INFINITE RECURSION")
        print(f"{Fore.MAGENTA}{'*'*80}")
        print(f"{Fore.WHITE}Generating deep recursion trees and complex branching")
        print(f"{Fore.YELLOW}Duration: 20 seconds")
        print(f"{Fore.RED}Warning: May cause stack overflow or Python interpreter crash")
        
        self.stop_signal = False
        recursion_depth = 0
        
        def recursive_bomb(depth, max_depth=1000):
            """Recursive function that creates complex branching"""
            if depth >= max_depth or self.stop_signal:
                return 1
            
            # Create multiple recursive branches
            result = 0
            for i in range(5):  # 5 branches per call
                x = recursive_bomb(depth + 1, max_depth)
                # Complex calculation with the result
                result += x ** 2 - math.sin(x) * math.cos(x) + math.tan(x/100)
            
            # Additional calculations
            result = result ** (1 + math.sin(depth))
            return result
        
        start_time = time.time()
        try:
            while time.time() - start_time < 20:
                recursion_depth += 100
                try:
                    # Try deep recursion
                    result = recursive_bomb(0, recursion_depth)
                    print(f"{Fore.CYAN}Recursion depth: {recursion_depth} | "
                          f"Result: {result:.2e} | Time: {time.time()-start_time:.1f}s | Ctrl+C to stop", end='\r')
                except RecursionError:
                    print(f"{Fore.YELLOW}RecursionError at depth {recursion_depth}, resetting...")
                    recursion_depth = 0
                except Exception as e:
                    print(f"{Fore.RED}Error: {e}")
        
        except KeyboardInterrupt:
            print(f"\n{Fore.YELLOW}Test stopped by user")
        finally:
            self.stop_signal = True
        
        print(f"\n{Fore.GREEN}✓ Level 8 completed!")
        print(f"{Fore.WHITE}Maximum recursion depth attempted: {recursion_depth}")
        input(f"\n{Fore.CYAN}Press Enter to continue...")
    
    # ============ LEVEL 9: BINARY BOMBARDMENT ============
    def run_level_9(self):
        """Bitwise operations at maximum speed"""
        print(f"\n{Fore.MAGENTA}{'*'*80}")
        print(f"{Fore.RED}LEVEL 9: BINARY BOMBARDMENT")
        print(f"{Fore.MAGENTA}{'*'*80}")
        print(f"{Fore.WHITE}Billions of bitwise operations per second")
        print(f"{Fore.YELLOW}Duration: 15 seconds")
        print(f"{Fore.RED}Warning: CPU will reach maximum temperature")
        
        start_time = time.time()
        operations = 0
        
        try:
            while time.time() - start_time < 15:
                # Create large arrays for bitwise operations
                size = 100000
                array1 = [random.getrandbits(64) for _ in range(size)]
                array2 = [random.getrandbits(64) for _ in range(size)]
                
                # Perform massive bitwise operations
                for i in range(size):
                    # Multiple bitwise operations
                    a = array1[i]
                    b = array2[i]
                    
                    # Chain of bitwise operations
                    result = a ^ b
                    result = result & (a | b)
                    result = result << (b & 31)
                    result = result >> (a & 31)
                    result = ~result
                    result = result ^ (a & b)
                    result = result | (a ^ ~b)
                    
                    # Store result
                    array1[i] = result
                
                operations += size
                
                # Additional: SHA-like operations
                for i in range(0, size, 100):
                    x = array1[i]
                    # Simulate hashing operations
                    for _ in range(100):
                        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9
                        x = (x ^ (x >> 27)) * 0x94d049bb133111eb
                        x = x ^ (x >> 31)
                    array2[i] = x
                
                elapsed = time.time() - start_time
                ops_per_sec = operations / elapsed if elapsed > 0 else 0
                print(f"{Fore.CYAN}Operations: {operations:,} | "
                      f"Ops/sec: {ops_per_sec:,.0f} | "
                      f"Time: {elapsed:.1f}s | Ctrl+C to stop", end='\r')
        
        except KeyboardInterrupt:
            print(f"\n{Fore.YELLOW}Test stopped by user")
        
        print(f"\n{Fore.GREEN}✓ Level 9 completed!")
        print(f"{Fore.WHITE}Total bitwise operations: {operations:,}")
        print(f"{Fore.WHITE}Average operations/second: {operations/15:,.0f}")
        input(f"\n{Fore.CYAN}Press Enter to continue...")
    
    # ============ LEVEL 10: I9 KILLER ============
    def run_level_10(self):
        """The ultimate CPU stress test designed to crash even i9 systems"""
        print(f"\n{Fore.RED}{'!'*100}")
        print(f"{Fore.RED}{' '*30}LEVEL 10: I9 KILLER")
        print(f"{Fore.RED}{'!'*100}")
        print(f"\n{Back.RED}{Fore.WHITE}{'EXTREME DANGER WARNING':^100}{Style.RESET_ALL}")
        print(f"\n{Fore.RED}THIS TEST IS DESIGNED TO:")
        print(f"{Fore.RED}• Push ALL CPU cores to 100% for extended period")
        print(f"{Fore.RED}• Use maximum available RAM")
        print(f"{Fore.RED}• Generate extreme heat (CPU temperature)")
        print(f"{Fore.RED}• Potentially cause:")
        print(f"{Fore.RED}  - System freeze/crash")
        print(f"{Fore.RED}  - Kernel panic")
        print(f"{Fore.RED}  - Thermal throttling/shutdown")
        print(f"{Fore.RED}  - Hardware damage (in extreme cases)")
        
        print(f"\n{Fore.YELLOW}Your System:")
        print(f"{Fore.WHITE}CPU: {self.cpu_name}")
        print(f"{Fore.WHITE}Cores: {self.core_count}")
        
        print(f"\n{Back.YELLOW}{Fore.BLACK} RECOMMENDED: DO NOT RUN ON LAPTOPS OR SYSTEMS WITH POOR COOLING {Style.RESET_ALL}")
        
        confirm = input(f"\n{Fore.RED}Type 'I9-KILLER-CONFIRM' to proceed: ")
        
        if confirm != 'I9-KILLER-CONFIRM':
            print(f"{Fore.YELLOW}Test cancelled - Wise choice!")
            input(f"\n{Fore.CYAN}Press Enter to continue...")
            return
        
        print(f"\n{Fore.RED}FINAL WARNING: Starting in 10 seconds...")
        for i in range(10, 0, -1):
            print(f"{Fore.RED}{i}...")
            time.sleep(1)
        
        print(f"{Fore.RED}{'*'*100}")
        print(f"{Fore.RED}{' '*35}I9 KILLER ACTIVATED")
        print(f"{Fore.RED}{'*'*100}")
        
        # Extreme stress components
        self.stop_signal = False
        extreme_threads = []
        
        def extreme_cpu_worker():
            """Worker that maximizes CPU usage with AVX-like instructions"""
            while not self.stop_signal:
                # Massive matrix operations (simulating AVX workloads)
                size = 500
                mat = [[random.random() for _ in range(size)] for _ in range(size)]
                
                # Simulate AVX/SSE vector operations
                for _ in range(100):
                    for i in range(size):
                        for j in range(size):
                            # Heavy floating-point operations
                            mat[i][j] = (mat[i][j] * 3.14159 + math.sin(mat[i][j])) ** 2.71828
                            mat[i][j] = math.exp(mat[i][j]) - math.log(abs(mat[i][j]) + 1)
                
                # Prime number calculation (CPU intensive)
                n = 100000
                sieve = [True] * n
                for i in range(2, int(n**0.5) + 1):
                    if sieve[i]:
                        for j in range(i*i, n, i):
                            sieve[j] = False
        
        def extreme_memory_worker():
            """Worker that continuously allocates and deallocates memory"""
            memory_pool = []
            while not self.stop_signal:
                # Allocate 500MB
                block = bytearray(500 * 1024 * 1024)
                memory_pool.append(block)
                
                # Process memory
                for i in range(0, len(block), 4096):
                    block[i] = (block[i] + 1) % 256
                
                # Keep memory pressure
                if len(memory_pool) > 10:
                    memory_pool.pop(0)
                
                time.sleep(0.1)
        
        def extreme_io_worker():
            """Worker that stresses I/O and system calls"""
            while not self.stop_signal:
                # Create and delete files
                temp_files = []
                for i in range(100):
                    with open(f'temp_{i}_{random.randint(1, 1000000)}.tmp', 'wb') as f:
                        f.write(os.urandom(1024 * 1024))  # 1MB each
                        temp_files.append(f.name)
                
                # Process them
                for fname in temp_files:
                    try:
                        os.remove(fname)
                    except:
                        pass
                
                time.sleep(0.5)
        
        def extreme_bit_worker():
            """Worker that does cryptographic-like operations"""
            while not self.stop_signal:
                # Simulate cryptographic hashing
                data = os.urandom(1024 * 1024)  # 1MB
                
                # Multiple rounds of transformation
                for _ in range(1000):
                    # SHA-like operations
                    result = bytearray(64)
                    for i in range(len(data)):
                        result[i % 64] ^= data[i]
                        result[(i + 17) % 64] = (result[(i + 17) % 64] + data[i]) % 256
                        result[(i + 31) % 64] = result[(i + 31) % 64] ^ (data[i] * 137) % 256
                
                time.sleep(0.01)
        
        # Start all workers
        print(f"{Fore.RED}Starting {self.core_count * 2} extreme stress threads...")
        
        # CPU workers (2 per core)
        for i in range(self.core_count * 2):
            t = threading.Thread(target=extreme_cpu_worker)
            t.daemon = True
            t.start()
            extreme_threads.append(t)
        
        # Memory worker
        mem_thread = threading.Thread(target=extreme_memory_worker)
        mem_thread.daemon = True
        mem_thread.start()
        extreme_threads.append(mem_thread)
        
        # I/O worker
        io_thread = threading.Thread(target=extreme_io_worker)
        io_thread.daemon = True
        io_thread.start()
        extreme_threads.append(io_thread)
        
        # Bit worker
        bit_thread = threading.Thread(target=extreme_bit_worker)
        bit_thread.daemon = True
        bit_thread.start()
        extreme_threads.append(bit_thread)
        
        # Monitor and run for 60 seconds or until crash
        start_time = time.time()
        print(f"{Fore.RED}I9 KILLER RUNNING - System may become unresponsive...")
        print(f"{Fore.YELLOW}Target duration: 60 seconds")
        
        try:
            while time.time() - start_time < 60:
                elapsed = time.time() - start_time
                print(f"{Fore.RED}Time: {elapsed:.1f}s / 60s | "
                      f"Threads: {len(extreme_threads)} | "
                      f"Status: SYSTEM UNDER EXTREME STRESS", end='\r')
                time.sleep(0.1)
                
                # Increase intensity over time
                if elapsed > 30 and elapsed < 45:
                    # Add more threads mid-way
                    if len(extreme_threads) < 50:
                        t = threading.Thread(target=extreme_cpu_worker)
                        t.daemon = True
                        t.start()
                        extreme_threads.append(t)
        
        except KeyboardInterrupt:
            print(f"\n{Fore.YELLOW}Emergency stop requested...")
        except Exception as e:
            print(f"\n{Fore.RED}System error: {e}")
        finally:
            # Try to stop threads
            self.stop_signal = True
            print(f"\n{Fore.YELLOW}Stopping all threads (may take a moment)...")
            
            # Clean up temp files
            for f in os.listdir('.'):
                if f.startswith('temp_') and f.endswith('.tmp'):
                    try:
                        os.remove(f)
                    except:
                        pass
        
        elapsed = time.time() - start_time
        print(f"\n{Fore.GREEN}{'='*100}")
        print(f"{Fore.YELLOW}I9 KILLER TEST COMPLETED")
        print(f"{Fore.GREEN}{'='*100}")
        print(f"{Fore.WHITE}Total duration: {elapsed:.2f} seconds")
        print(f"{Fore.WHITE}Maximum threads: {len(extreme_threads)}")
        
        if elapsed >= 59:
            print(f"{Fore.GREEN}✓ Your system SURVIVED the I9 Killer test!")
            print(f"{Fore.YELLOW}Your CPU is extremely resilient!")
        elif elapsed >= 30:
            print(f"{Fore.YELLOW}⚠ Your system handled moderate stress")
            print(f"{Fore.YELLOW}Consider better cooling for extreme workloads")
        else:
            print(f"{Fore.RED}✗ Your system could not handle the stress")
            print(f"{Fore.YELLOW}System may have crashed or become unresponsive")
        
        input(f"\n{Fore.CYAN}Press Enter to continue...")
    
    # ============ LEVELS 1-4 (Simplified versions) ============
    def run_level_1(self):
        """Light CPU load"""
        print(f"\n{Fore.GREEN}Running Level 1 - Light CPU Load")
        print(f"{Fore.WHITE}Simple calculations for 10 seconds...")
        
        start_time = time.time()
        count = 0
        
        try:
            while time.time() - start_time < 10:
                for i in range(1000):
                    a = random.random()
                    b = a * 3.14159
                    c = b ** 2
                    count += 1
                
                print(f"{Fore.WHITE}Operations: {count:,}", end='\r')
            
            print(f"\n{Fore.GREEN}✓ Level 1 completed!")
            print(f"{Fore.WHITE}Total operations: {count:,}")
            
        except KeyboardInterrupt:
            print(f"\n{Fore.YELLOW}Test interrupted")
        
        input(f"\n{Fore.CYAN}Press Enter to continue...")
    
    def run_level_2(self):
        """Medium CPU load"""
        print(f"\n{Fore.YELLOW}Running Level 2 - Medium CPU Load")
        print(f"{Fore.WHITE}Multiple operations for 15 seconds...")
        
        start_time = time.time()
        results = []
        
        try:
            while time.time() - start_time < 15:
                matrix = []
                for i in range(50):
                    row = [random.random() for _ in range(50)]
                    matrix.append(row)
                
                for i in range(len(matrix)):
                    for j in range(len(matrix[i])):
                        matrix[i][j] = matrix[i][j] ** 3 - matrix[i][j] ** 2 + matrix[i][j]
                
                results.append(matrix)
                print(f"{Fore.WHITE}Matrices processed: {len(results)}", end='\r')
            
            print(f"\n{Fore.GREEN}✓ Level 2 completed!")
            print(f"{Fore.WHITE}Matrices processed: {len(results)}")
            
        except KeyboardInterrupt:
            print(f"\n{Fore.YELLOW}Test interrupted")
        
        input(f"\n{Fore.CYAN}Press Enter to continue...")
    
    def run_level_3(self):
        """Heavy CPU load"""
        print(f"\n{Fore.RED}Running Level 3 - Heavy CPU Load")
        print(f"{Fore.WHITE}Complex mathematics for 20 seconds...")
        
        start_time = time.time()
        iteration = 0
        
        try:
            while time.time() - start_time < 20:
                iteration += 1
                data = [random.randint(1, 1000000) for _ in range(10000)]
                data = [x ** 2 + x ** 1.5 - x ** 0.5 for x in data]
                data.sort()
                data = [x * 3.14159 / (i+1) for i, x in enumerate(data)]
                print(f"{Fore.WHITE}Iteration {iteration} | Data points: {len(data):,}", end='\r')
            
            print(f"\n{Fore.GREEN}✓ Level 3 completed!")
            print(f"{Fore.WHITE}Iterations: {iteration}")
            
        except KeyboardInterrupt:
            print(f"\n{Fore.YELLOW}Test interrupted")
        
        input(f"\n{Fore.CYAN}Press Enter to continue...")
    
    def run_level_4(self):
        """Extreme CPU load"""
        print(f"\n{Fore.MAGENTA}Running Level 4 - Extreme CPU Load")
        print(f"{Fore.WHITE}Memory intensive operations for 25 seconds...")
        
        start_time = time.time()
        operations = 0
        
        try:
            while time.time() - start_time < 25:
                operations += 1
                mega_list = []
                for i in range(100):
                    sublist = []
                    for j in range(100):
                        subsublist = [random.random() for _ in range(100)]
                        sublist.append(subsublist)
                    mega_list.append(sublist)
                
                total = 0
                for i in range(len(mega_list)):
                    for j in range(len(mega_list[i])):
                        for k in range(len(mega_list[i][j])):
                            mega_list[i][j][k] = mega_list[i][j][k] ** random.random()
                            total += mega_list[i][j][k]
                
                print(f"{Fore.WHITE}Operations: {operations} | Total sum: {total:,.2f}", end='\r')
            
            print(f"\n{Fore.GREEN}✓ Level 4 completed!")
            print(f"{Fore.WHITE}Total operations: {operations}")
            
        except KeyboardInterrupt:
            print(f"\n{Fore.YELLOW}Test interrupted")
        
        input(f"\n{Fore.CYAN}Press Enter to continue...")
    
    # ============ MAIN MENU ============
    def main_menu(self):
        while True:
            self.display_header()
            
            print(f"{Fore.GREEN}CPU STRESS TEST LEVELS:")
            for level in range(1, 11):
                desc = self.level_descriptions[level]
                if level <= 4:
                    color = Fore.GREEN
                elif level <= 7:
                    color = Fore.YELLOW
                elif level <= 9:
                    color = Fore.RED
                else:  # Level 10
                    color = Fore.RED + Style.BRIGHT
                print(f"  {color}Level {level}: {desc}")
            
            print(f"\n{Fore.MAGENTA}Special Options:")
            print(f"  {Fore.CYAN}J: Configure Jupyter Notebook IOPUB Settings")
            print(f"  {Fore.CYAN}S: System Information")
            print(f"  {Fore.CYAN}Q: Quit Program")
            
            choice = input(f"\n{Fore.WHITE}Select test level (1-10) or option: ").strip().upper()
            
            if choice == 'Q':
                print(f"\n{Fore.YELLOW}Thank you for using Ultimate CPU Stress Tester!")
                break
            elif choice == 'J':
                while self.display_jupyter_menu():
                    pass
            elif choice == 'S':
                self.display_header()
                print(f"{Fore.CYAN}System Information:")
                print(f"{Fore.WHITE}CPU: {self.cpu_name}")
                print(f"{Fore.WHITE}Cores/Threads: {self.core_count}")
                print(f"{Fore.WHITE}Platform: {platform.platform()}")
                print(f"{Fore.WHITE}Python: {sys.version}")
                input(f"\n{Fore.CYAN}Press Enter to continue...")
            elif choice in [str(i) for i in range(1, 11)]:
                level = int(choice)
                
                self.display_header()
                print(f"{Fore.CYAN}Selected: Level {level} - {self.level_descriptions[level]}")
                
                # Special warnings for dangerous levels
                if level == 5:
                    print(f"\n{Fore.RED}{'!'*80}")
                    print(f"{Fore.RED}This is the ORIGINAL unmodified stress code")
                    print(f"{Fore.RED}{'!'*80}")
                    
                    confirm = input(f"{Fore.YELLOW}Type 'YES-RUN-ORIGINAL' to continue: ")
                    
                    if confirm == 'YES-RUN-ORIGINAL':
                        try:
                            self.run_level_5()
                        except UserDenialError as e:
                            print(f"{Fore.YELLOW}{e}")
                            input(f"\n{Fore.CYAN}Press Enter to continue...")
                    else:
                        print(f"{Fore.YELLOW}Test cancelled")
                        input(f"\n{Fore.CYAN}Press Enter to continue...")
                
                elif level == 10:
                    print(f"\n{Back.RED}{Fore.WHITE}{'EXTREME DANGER':^80}{Style.RESET_ALL}")
                    confirm = input(f"{Fore.RED}Type 'ACCEPT-CRASH-RISK' to continue: ")
                    
                    if confirm == 'ACCEPT-CRASH-RISK':
                        self.run_level_10()
                    else:
                        print(f"{Fore.YELLOW}Test cancelled - Wise choice!")
                        input(f"\n{Fore.CYAN}Press Enter to continue...")
                
                else:
                    # For other levels, just run them
                    if level == 1:
                        self.run_level_1()
                    elif level == 2:
                        self.run_level_2()
                    elif level == 3:
                        self.run_level_3()
                    elif level == 4:
                        self.run_level_4()
                    elif level == 6:
                        self.run_level_6()
                    elif level == 7:
                        self.run_level_7()
                    elif level == 8:
                        self.run_level_8()
                    elif level == 9:
                        self.run_level_9()
            else:
                print(f"{Fore.RED}Invalid selection")
                time.sleep(1)

def main():
    print(f"{Fore.CYAN}{'='*100}")
    print(f"{Fore.YELLOW}{' '*30}ULTIMATE CPU STRESS TESTER v2.0")
    print(f"{Fore.CYAN}{'='*100}")
    print(f"{Fore.WHITE}Now with 10 levels of CPU torture testing!")
    print(f"{Fore.RED}Level 10 specifically designed to stress even i9 CPUs to their limits")
    time.sleep(3)
    
    game = CPUTestGame()
    
    try:
        game.main_menu()
    except KeyboardInterrupt:
        print(f"\n\n{Fore.YELLOW}Program terminated by user")
        sys.exit(0)
    except Exception as e:
        print(f"\n{Fore.RED}Fatal error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

if __name__ == "__main__":
    # Install psutil if needed
    try:
        import psutil
    except ImportError:
        print(f"{Fore.YELLOW}Installing psutil for system monitoring...")
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install", "psutil"])
            import psutil
            print(f"{Fore.GREEN}psutil installed successfully!")
            time.sleep(2)
        except:
            print(f"{Fore.YELLOW}Could not install psutil. Some features may be limited.")
            time.sleep(2)
    
    main()
