"""
RGD-PHYSICS :: DISCRETE GEOMETRY (CFT KERNEL)
Implements Spacetime as a Lattice Vector Field.
"""
import math
from ..core.interfaces import GeometryKernel, Microsecond
from ..chronon.interfaces import ChrononProtocol
from ..core.exceptions import CausalityBreak, QuantumDecoherence

class DiscreteGeometry(GeometryKernel):
    """
    The CFT Standard Kernel (Lattice).
    Treats spacetime as a discrete grid directed by causal vectors.
    Rejects the continuum hypothesis.
    """
    
    def check_structural_integrity(self, t0: ChrononProtocol, t1: ChrononProtocol, dt: Microsecond) -> None:
        # 1. DECODE LOCAL PHYSICS (The Field State at T0)
        # The 'laws_encoded' field tells us the density of spacetime at this location.
        delta_raw = t0.laws_encoded
        
        # Extract Scale (3 bits) and Mantissa (21 bits) via bitmasking
        # Scale determines the Order of Magnitude (Macro vs Quantum).
        scale_idx = (delta_raw >> 29) & 0b111
        mantissa = delta_raw & 0x1FFFFF
        
        # Calculate Synthetic Planck Time (Minimum Resolution)
        # Higher scale index = Finer grid resolution.
        # Scale 0 (Macro) ~ 1ms | Scale 7 (Quantum) ~ 1ns
        # Formula: 1ms * 10^(-scale)
        min_time_resolution = 1e-3 * (10 ** (-scale_idx))
        
        # CHECK 1: QUANTUM NOISE (Heisenberg Cutoff)
        # If the entity tries to act within a timeframe smaller than the lattice resolution,
        # the action is physically undefined. It is treated as quantum noise.
        if dt < min_time_resolution:
            raise QuantumDecoherence(
                f"CFT VIOLATION: Interval {dt:.2e}s is below local Planck Scale {min_time_resolution:.2e}s"
            )

        # 2. VECTOR FIELD ALIGNMENT (Light Cone Check)
        # Calculate Local Speed of Light (c_local) based on the mantissa.
        # Offset -4 allows handling speeds from microscopic to relativistic.
        magnitude = scale_idx - 4
        c_local = float(mantissa * (10 ** magnitude))
        
        # Calculate 4D Euclidean Distance (Hyperspace)
        # We include 'w' (Probability Branch) because jumping between timelines costs 'distance'.
        x0, y0, z0, w0 = t0.metric_coordinates
        x1, y1, z1, w1 = t1.metric_coordinates
        
        distance = math.sqrt(
            (x1 - x0)**2 + (y1 - y0)**2 + (z1 - z0)**2 + (w1 - w0)**2
        )
        
        # CHECK 2: CAUSALITY BREAK (Event Horizon)
        # The distance traveled cannot exceed (Speed of Light * Time Elapsed).
        # This enforces the Relativistic Light Cone.
        max_valid_distance = c_local * dt
        
        if distance > max_valid_distance:
            raise CausalityBreak(
                f"EVENT HORIZON: Attempted jump {distance:.4f} exceeds Light Cone radius {max_valid_distance:.4f}"
            )