import base64
import os

def getBytesWithSize(data):
    """
    Read length-prefixed data.
    Format: [size:4 bytes big-endian][data:size bytes]
    Returns: (data_bytes, remaining_bytes)
    """
    if len(data) < 4:
        print(f"[WARN] getBytesWithSize: datos insuficientes ({len(data)} < 4)")
        return b"", data
    
    size = int.from_bytes(data[0:4], 'big')  # Explicitly use big-endian
    data = data[4:]
    
    # Validate size (reasonable limit: 100MB)
    MAX_REASONABLE_SIZE = 100 * 1024 * 1024
    if size > MAX_REASONABLE_SIZE:
        print(f"[WARN] getBytesWithSize: tamaño sospechoso ({size} bytes, max razonable: {MAX_REASONABLE_SIZE})")
        # Removed hex dump - use debug logging if needed
        # If size is suspicious, maybe it's actually a marker byte
        # Return empty output and keep all data as remaining
        return b"", data
    
    if len(data) < size:
        print(f"[WARN] getBytesWithSize: tamaño ({size}) mayor que datos disponibles ({len(data)})")
        # Return what we can and empty remaining
        return data[:size], b""
    
    return data[:size], data[size:]