"""
RGD-PHYSICS :: AION-4096 (The Soul)
512-Byte Alignment (8 Cache Lines).
Ideal for AGI States, Deep Simulation Snapshots, and High-Fidelity Transfer.
"""
import struct
from dataclasses import dataclass
from typing import Tuple

@dataclass(frozen=True, slots=True)
class Aion4096:
    """
    The God-Scale Atom.
    Carries massive cognitive payloads embedded in spacetime.
    Total Size: 512 Bytes.

    Structure (64 x 64-bit Integers):
    [0-3]   Header (Anchor, Metric Lo/Hi, Meta) - 32 Bytes
    [4-63]  Payload (60 Integers) - 480 Bytes
    """
    # --- HEADER (32 Bytes / 4 Integers) ---
    anchor: int      
    metric_lo: int   
    metric_hi: int   
    meta_data: int   

    # --- DEEP PAYLOAD (480 Bytes / 60 Integers) ---
    # We use a Tuple of ints for immutability and fast hashing.
    # Must contain exactly 60 unsigned long longs.
    p_data: Tuple[int, ...] 

    @property
    def aion_class(self) -> str:
        return "HEAVY (4096-bit)"

    # --- PROTOCOL IMPLEMENTATION ---

    @property
    def laws_encoded(self) -> int:
        return (self.meta_data >> 32) & 0xFFFFFFFF

    @property
    def metric_coordinates(self) -> Tuple[float, float, float, float]:
        # Standard unpacking logic
        x_int = (self.metric_lo >> 32) & 0xFFFFFFFF
        y_int = self.metric_lo & 0xFFFFFFFF
        z_int = (self.metric_hi >> 32) & 0xFFFFFFFF
        w_int = self.metric_hi & 0xFFFFFFFF
        scale = 1000.0
        return (x_int/scale, y_int/scale, z_int/scale, w_int/scale)

    @property
    def payload_hash(self) -> int:
        """
        Fast Audit Hash.
        Instead of iterating 60 items, we XOR the boundaries and the center.
        This provides a statistical fingerprint sufficient for Entropy checks.
        """
        if not self.p_data: return 0
        # XOR Start, Middle, End
        return self.p_data[0] ^ self.p_data[30] ^ self.p_data[-1]

    # --- ZERO-COPY SERIALIZATION ---
    
    # 64 Unsigned Long Longs = 512 Bytes
    _STRUCT = struct.Struct('!64Q')

    def to_bytes(self) -> bytes:
        """Serializes header + payload tuple into 512 bytes raw."""
        if len(self.p_data) != 60:
             raise ValueError(f"Aion4096 requires exactly 60 payload integers, got {len(self.p_data)}")
        
        # We flatten the header fields and the payload tuple into a single argument list
        return self._STRUCT.pack(
            self.anchor, 
            self.metric_lo, 
            self.metric_hi, 
            self.meta_data, 
            *self.p_data
        )

    @classmethod
    def from_bytes(cls, buffer: bytes) -> 'Aion4096':
        unpacked = cls._STRUCT.unpack(buffer)
        # Slicing: First 4 are header, the rest (4:) is payload
        return cls(
            anchor=unpacked[0],
            metric_lo=unpacked[1],
            metric_hi=unpacked[2],
            meta_data=unpacked[3],
            p_data=unpacked[4:]
        )